blob: 02a5a0807bb18e5c34bb8808d1beaa1cc4ff6ce6 [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;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700206 // uint32_t pointerCount
207 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800208 // nsecs_t eventTime
209 msg->body.motion.eventTime = body.motion.eventTime;
210 // int32_t deviceId
211 msg->body.motion.deviceId = body.motion.deviceId;
212 // int32_t source
213 msg->body.motion.source = body.motion.source;
214 // int32_t displayId
215 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600216 // std::array<uint8_t, 32> hmac
217 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800218 // int32_t action
219 msg->body.motion.action = body.motion.action;
220 // int32_t actionButton
221 msg->body.motion.actionButton = body.motion.actionButton;
222 // int32_t flags
223 msg->body.motion.flags = body.motion.flags;
224 // int32_t metaState
225 msg->body.motion.metaState = body.motion.metaState;
226 // int32_t buttonState
227 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800228 // MotionClassification classification
229 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800230 // int32_t edgeFlags
231 msg->body.motion.edgeFlags = body.motion.edgeFlags;
232 // nsecs_t downTime
233 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700234
235 msg->body.motion.dsdx = body.motion.dsdx;
236 msg->body.motion.dtdx = body.motion.dtdx;
237 msg->body.motion.dtdy = body.motion.dtdy;
238 msg->body.motion.dsdy = body.motion.dsdy;
239 msg->body.motion.tx = body.motion.tx;
240 msg->body.motion.ty = body.motion.ty;
241
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800242 // float xPrecision
243 msg->body.motion.xPrecision = body.motion.xPrecision;
244 // float yPrecision
245 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700246 // float xCursorPosition
247 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
248 // float yCursorPosition
249 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700250
251 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
252 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
253 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
254 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
255 msg->body.motion.txRaw = body.motion.txRaw;
256 msg->body.motion.tyRaw = body.motion.tyRaw;
257
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800258 //struct Pointer pointers[MAX_POINTERS]
259 for (size_t i = 0; i < body.motion.pointerCount; i++) {
260 // PointerProperties properties
261 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
262 msg->body.motion.pointers[i].properties.toolType =
263 body.motion.pointers[i].properties.toolType,
264 // PointerCoords coords
265 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
266 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
267 memcpy(&msg->body.motion.pointers[i].coords.values[0],
268 &body.motion.pointers[i].coords.values[0],
269 count * (sizeof(body.motion.pointers[i].coords.values[0])));
270 }
271 break;
272 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700273 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800274 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000275 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800276 break;
277 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800278 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800279 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800280 msg->body.focus.hasFocus = body.focus.hasFocus;
281 msg->body.focus.inTouchMode = body.focus.inTouchMode;
282 break;
283 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800284 case InputMessage::Type::CAPTURE: {
285 msg->body.capture.eventId = body.capture.eventId;
286 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
287 break;
288 }
arthurhung7632c332020-12-30 16:58:01 +0800289 case InputMessage::Type::DRAG: {
290 msg->body.drag.eventId = body.drag.eventId;
291 msg->body.drag.x = body.drag.x;
292 msg->body.drag.y = body.drag.y;
293 msg->body.drag.isExiting = body.drag.isExiting;
294 break;
295 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000296 case InputMessage::Type::TIMELINE: {
297 msg->body.timeline.eventId = body.timeline.eventId;
298 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
299 break;
300 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700301 case InputMessage::Type::TOUCH_MODE: {
302 msg->body.touchMode.eventId = body.touchMode.eventId;
303 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
304 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800305 }
306}
Jeff Brown5912f952013-07-01 19:10:31 -0700307
308// --- InputChannel ---
309
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500310std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500311 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700312 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
313 if (result != 0) {
314 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
315 strerror(errno));
316 return nullptr;
317 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500318 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500319 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700320}
321
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500322InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
323 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700324 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500325 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700326 }
Jeff Brown5912f952013-07-01 19:10:31 -0700327}
328
329InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700330 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500331 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700332 }
Robert Carr3720ed02018-08-08 16:08:27 -0700333}
334
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800335status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500336 std::unique_ptr<InputChannel>& outServerChannel,
337 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700338 int sockets[2];
339 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
340 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000341 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
342 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500343 outServerChannel.reset();
344 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700345 return result;
346 }
347
348 int bufferSize = SOCKET_BUFFER_SIZE;
349 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
350 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
351 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
352 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
353
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700354 sp<IBinder> token = new BBinder();
355
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700356 std::string serverChannelName = name + " (server)";
357 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700358 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700359
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700360 std::string clientChannelName = name + " (client)";
361 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700362 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700363 return OK;
364}
365
366status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800367 const size_t msgLength = msg->size();
368 InputMessage cleanMsg;
369 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700370 ssize_t nWrite;
371 do {
Chris Ye0783e992020-06-02 21:34:49 -0700372 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700373 } while (nWrite == -1 && errno == EINTR);
374
375 if (nWrite < 0) {
376 int error = errno;
377#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800378 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
379 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700380#endif
381 if (error == EAGAIN || error == EWOULDBLOCK) {
382 return WOULD_BLOCK;
383 }
384 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
385 return DEAD_OBJECT;
386 }
387 return -error;
388 }
389
390 if (size_t(nWrite) != msgLength) {
391#if DEBUG_CHANNEL_MESSAGES
392 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800393 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700394#endif
395 return DEAD_OBJECT;
396 }
397
398#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800399 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700400#endif
401 return OK;
402}
403
404status_t InputChannel::receiveMessage(InputMessage* msg) {
405 ssize_t nRead;
406 do {
Chris Ye0783e992020-06-02 21:34:49 -0700407 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700408 } while (nRead == -1 && errno == EINTR);
409
410 if (nRead < 0) {
411 int error = errno;
412#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800413 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700414#endif
415 if (error == EAGAIN || error == EWOULDBLOCK) {
416 return WOULD_BLOCK;
417 }
418 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
419 return DEAD_OBJECT;
420 }
421 return -error;
422 }
423
424 if (nRead == 0) { // check for EOF
425#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800426 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700427#endif
428 return DEAD_OBJECT;
429 }
430
431 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000432 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700433 return BAD_VALUE;
434 }
435
436#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800437 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700438#endif
439 return OK;
440}
441
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500442std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700443 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700444 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700445}
446
Garfield Tan15601662020-09-22 15:32:38 -0700447void InputChannel::copyTo(InputChannel& outChannel) const {
448 outChannel.mName = getName();
449 outChannel.mFd = dupFd();
450 outChannel.mToken = getConnectionToken();
451}
452
Chris Ye0783e992020-06-02 21:34:49 -0700453status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500454 if (parcel == nullptr) {
455 ALOGE("%s: Null parcel", __func__);
456 return BAD_VALUE;
457 }
458 return parcel->writeStrongBinder(mToken)
459 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700460}
461
Chris Ye0783e992020-06-02 21:34:49 -0700462status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500463 if (parcel == nullptr) {
464 ALOGE("%s: Null parcel", __func__);
465 return BAD_VALUE;
466 }
467 mToken = parcel->readStrongBinder();
468 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700469}
470
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700471sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500472 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700473}
474
Garfield Tan15601662020-09-22 15:32:38 -0700475base::unique_fd InputChannel::dupFd() const {
476 android::base::unique_fd newFd(::dup(getFd()));
477 if (!newFd.ok()) {
478 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
479 strerror(errno));
480 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
481 // If this process is out of file descriptors, then throwing that might end up exploding
482 // on the other side of a binder call, which isn't really helpful.
483 // Better to just crash here and hope that the FD leak is slow.
484 // Other failures could be client errors, so we still propagate those back to the caller.
485 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
486 getName().c_str());
487 return {};
488 }
489 return newFd;
490}
491
Jeff Brown5912f952013-07-01 19:10:31 -0700492// --- InputPublisher ---
493
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500494InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700495
496InputPublisher::~InputPublisher() {
497}
498
Garfield Tan1c7bc862020-01-28 13:24:04 -0800499status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
500 int32_t source, int32_t displayId,
501 std::array<uint8_t, 32> hmac, int32_t action,
502 int32_t flags, int32_t keyCode, int32_t scanCode,
503 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
504 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000505 if (ATRACE_ENABLED()) {
506 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
507 mChannel->getName().c_str(), keyCode);
508 ATRACE_NAME(message.c_str());
509 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800510 if (DEBUG_TRANSPORT_ACTIONS) {
511 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
512 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
513 "downTime=%" PRId64 ", eventTime=%" PRId64,
514 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
515 metaState, repeatCount, downTime, eventTime);
516 }
Jeff Brown5912f952013-07-01 19:10:31 -0700517
518 if (!seq) {
519 ALOGE("Attempted to publish a key event with sequence number 0.");
520 return BAD_VALUE;
521 }
522
523 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700524 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500525 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800526 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700527 msg.body.key.deviceId = deviceId;
528 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100529 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700530 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700531 msg.body.key.action = action;
532 msg.body.key.flags = flags;
533 msg.body.key.keyCode = keyCode;
534 msg.body.key.scanCode = scanCode;
535 msg.body.key.metaState = metaState;
536 msg.body.key.repeatCount = repeatCount;
537 msg.body.key.downTime = downTime;
538 msg.body.key.eventTime = eventTime;
539 return mChannel->sendMessage(&msg);
540}
541
542status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800543 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600544 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
545 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700546 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700547 float yPrecision, float xCursorPosition, float yCursorPosition,
548 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700549 uint32_t pointerCount, const PointerProperties* pointerProperties,
550 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000551 if (ATRACE_ENABLED()) {
552 std::string message = StringPrintf(
553 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
554 mChannel->getName().c_str(), action);
555 ATRACE_NAME(message.c_str());
556 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800557 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700558 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700559 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800560 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
561 "displayId=%" PRId32 ", "
562 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700563 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800564 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700565 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800566 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
567 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700568 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
569 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800570 }
Jeff Brown5912f952013-07-01 19:10:31 -0700571
572 if (!seq) {
573 ALOGE("Attempted to publish a motion event with sequence number 0.");
574 return BAD_VALUE;
575 }
576
577 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700578 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800579 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700580 return BAD_VALUE;
581 }
582
583 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700584 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500585 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800586 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700587 msg.body.motion.deviceId = deviceId;
588 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700589 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700590 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700591 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100592 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700593 msg.body.motion.flags = flags;
594 msg.body.motion.edgeFlags = edgeFlags;
595 msg.body.motion.metaState = metaState;
596 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800597 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700598 msg.body.motion.dsdx = transform.dsdx();
599 msg.body.motion.dtdx = transform.dtdx();
600 msg.body.motion.dtdy = transform.dtdy();
601 msg.body.motion.dsdy = transform.dsdy();
602 msg.body.motion.tx = transform.tx();
603 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700604 msg.body.motion.xPrecision = xPrecision;
605 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700606 msg.body.motion.xCursorPosition = xCursorPosition;
607 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700608 msg.body.motion.dsdxRaw = rawTransform.dsdx();
609 msg.body.motion.dtdxRaw = rawTransform.dtdx();
610 msg.body.motion.dtdyRaw = rawTransform.dtdy();
611 msg.body.motion.dsdyRaw = rawTransform.dsdy();
612 msg.body.motion.txRaw = rawTransform.tx();
613 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700614 msg.body.motion.downTime = downTime;
615 msg.body.motion.eventTime = eventTime;
616 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100617 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700618 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
619 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
620 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700621
Jeff Brown5912f952013-07-01 19:10:31 -0700622 return mChannel->sendMessage(&msg);
623}
624
Garfield Tan1c7bc862020-01-28 13:24:04 -0800625status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
626 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800627 if (ATRACE_ENABLED()) {
628 std::string message =
629 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
630 mChannel->getName().c_str(), toString(hasFocus),
631 toString(inTouchMode));
632 ATRACE_NAME(message.c_str());
633 }
634
635 InputMessage msg;
636 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500637 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800638 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000639 msg.body.focus.hasFocus = hasFocus;
640 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800641 return mChannel->sendMessage(&msg);
642}
643
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800644status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
645 bool pointerCaptureEnabled) {
646 if (ATRACE_ENABLED()) {
647 std::string message =
648 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
649 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
650 ATRACE_NAME(message.c_str());
651 }
652
653 InputMessage msg;
654 msg.header.type = InputMessage::Type::CAPTURE;
655 msg.header.seq = seq;
656 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000657 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800658 return mChannel->sendMessage(&msg);
659}
660
arthurhung7632c332020-12-30 16:58:01 +0800661status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
662 bool isExiting) {
663 if (ATRACE_ENABLED()) {
664 std::string message =
665 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
666 mChannel->getName().c_str(), x, y, toString(isExiting));
667 ATRACE_NAME(message.c_str());
668 }
669
670 InputMessage msg;
671 msg.header.type = InputMessage::Type::DRAG;
672 msg.header.seq = seq;
673 msg.body.drag.eventId = eventId;
674 msg.body.drag.isExiting = isExiting;
675 msg.body.drag.x = x;
676 msg.body.drag.y = y;
677 return mChannel->sendMessage(&msg);
678}
679
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700680status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
681 if (ATRACE_ENABLED()) {
682 std::string message =
683 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
684 mChannel->getName().c_str(), toString(isInTouchMode));
685 ATRACE_NAME(message.c_str());
686 }
687
688 InputMessage msg;
689 msg.header.type = InputMessage::Type::TOUCH_MODE;
690 msg.header.seq = seq;
691 msg.body.touchMode.eventId = eventId;
692 msg.body.touchMode.isInTouchMode = isInTouchMode;
693 return mChannel->sendMessage(&msg);
694}
695
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000696android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800697 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000698 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800699 }
Jeff Brown5912f952013-07-01 19:10:31 -0700700
701 InputMessage msg;
702 status_t result = mChannel->receiveMessage(&msg);
703 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000704 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700705 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000706 if (msg.header.type == InputMessage::Type::FINISHED) {
707 return Finished{
708 .seq = msg.header.seq,
709 .handled = msg.body.finished.handled,
710 .consumeTime = msg.body.finished.consumeTime,
711 };
Jeff Brown5912f952013-07-01 19:10:31 -0700712 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000713
714 if (msg.header.type == InputMessage::Type::TIMELINE) {
715 return Timeline{
716 .inputEventId = msg.body.timeline.eventId,
717 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
718 };
719 }
720
721 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800722 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000723 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700724}
725
726// --- InputConsumer ---
727
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500728InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
729 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700730
731InputConsumer::~InputConsumer() {
732}
733
734bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600735 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700736}
737
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800738status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
739 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800740 if (DEBUG_TRANSPORT_ACTIONS) {
741 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
742 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
743 }
Jeff Brown5912f952013-07-01 19:10:31 -0700744
745 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700746 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700747
748 // Fetch the next input message.
749 // Loop until an event can be returned or no additional events are received.
750 while (!*outEvent) {
751 if (mMsgDeferred) {
752 // mMsg contains a valid input message from the previous call to consume
753 // that has not yet been processed.
754 mMsgDeferred = false;
755 } else {
756 // Receive a fresh message.
757 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000758 if (result == OK) {
759 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
760 }
Jeff Brown5912f952013-07-01 19:10:31 -0700761 if (result) {
762 // Consume the next batched event unless batches are being held for later.
763 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800764 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700765 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800766 if (DEBUG_TRANSPORT_ACTIONS) {
767 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
768 mChannel->getName().c_str(), *outSeq);
769 }
Jeff Brown5912f952013-07-01 19:10:31 -0700770 break;
771 }
772 }
773 return result;
774 }
775 }
776
777 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700778 case InputMessage::Type::KEY: {
779 KeyEvent* keyEvent = factory->createKeyEvent();
780 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700781
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700782 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500783 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700784 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800785 if (DEBUG_TRANSPORT_ACTIONS) {
786 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
787 mChannel->getName().c_str(), *outSeq);
788 }
Jeff Brown5912f952013-07-01 19:10:31 -0700789 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700790 }
Jeff Brown5912f952013-07-01 19:10:31 -0700791
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700792 case InputMessage::Type::MOTION: {
793 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
794 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500795 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700796 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500797 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800798 if (DEBUG_TRANSPORT_ACTIONS) {
799 ALOGD("channel '%s' consumer ~ appended to batch event",
800 mChannel->getName().c_str());
801 }
Jeff Brown5912f952013-07-01 19:10:31 -0700802 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700803 } else if (isPointerEvent(mMsg.body.motion.source) &&
804 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
805 // No need to process events that we are going to cancel anyways
806 const size_t count = batch.samples.size();
807 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500808 const InputMessage& msg = batch.samples[i];
809 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700810 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500811 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
812 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700813 } else {
814 // We cannot append to the batch in progress, so we need to consume
815 // the previous batch right now and defer the new message until later.
816 mMsgDeferred = true;
817 status_t result = consumeSamples(factory, batch, batch.samples.size(),
818 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500819 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700820 if (result) {
821 return result;
822 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800823 if (DEBUG_TRANSPORT_ACTIONS) {
824 ALOGD("channel '%s' consumer ~ consumed batch event and "
825 "deferred current event, seq=%u",
826 mChannel->getName().c_str(), *outSeq);
827 }
Jeff Brown5912f952013-07-01 19:10:31 -0700828 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700829 }
Jeff Brown5912f952013-07-01 19:10:31 -0700830 }
Jeff Brown5912f952013-07-01 19:10:31 -0700831
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800832 // Start a new batch if needed.
833 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
834 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500835 Batch batch;
836 batch.samples.push_back(mMsg);
837 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800838 if (DEBUG_TRANSPORT_ACTIONS) {
839 ALOGD("channel '%s' consumer ~ started batch event",
840 mChannel->getName().c_str());
841 }
842 break;
843 }
Jeff Brown5912f952013-07-01 19:10:31 -0700844
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800845 MotionEvent* motionEvent = factory->createMotionEvent();
846 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700847
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800848 updateTouchState(mMsg);
849 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500850 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800851 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800852
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800853 if (DEBUG_TRANSPORT_ACTIONS) {
854 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
855 mChannel->getName().c_str(), *outSeq);
856 }
857 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700858 }
Jeff Brown5912f952013-07-01 19:10:31 -0700859
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000860 case InputMessage::Type::FINISHED:
861 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000862 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
863 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800864 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800865 break;
866 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800867
868 case InputMessage::Type::FOCUS: {
869 FocusEvent* focusEvent = factory->createFocusEvent();
870 if (!focusEvent) return NO_MEMORY;
871
872 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500873 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800874 *outEvent = focusEvent;
875 break;
876 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800877
878 case InputMessage::Type::CAPTURE: {
879 CaptureEvent* captureEvent = factory->createCaptureEvent();
880 if (!captureEvent) return NO_MEMORY;
881
882 initializeCaptureEvent(captureEvent, &mMsg);
883 *outSeq = mMsg.header.seq;
884 *outEvent = captureEvent;
885 break;
886 }
arthurhung7632c332020-12-30 16:58:01 +0800887
888 case InputMessage::Type::DRAG: {
889 DragEvent* dragEvent = factory->createDragEvent();
890 if (!dragEvent) return NO_MEMORY;
891
892 initializeDragEvent(dragEvent, &mMsg);
893 *outSeq = mMsg.header.seq;
894 *outEvent = dragEvent;
895 break;
896 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700897
898 case InputMessage::Type::TOUCH_MODE: {
899 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
900 if (!touchModeEvent) return NO_MEMORY;
901
902 initializeTouchModeEvent(touchModeEvent, &mMsg);
903 *outSeq = mMsg.header.seq;
904 *outEvent = touchModeEvent;
905 break;
906 }
Jeff Brown5912f952013-07-01 19:10:31 -0700907 }
908 }
909 return OK;
910}
911
912status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800913 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700914 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700915 for (size_t i = mBatches.size(); i > 0; ) {
916 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500917 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700918 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800919 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500920 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700921 return result;
922 }
923
Michael Wright32232172013-10-21 12:05:22 -0700924 nsecs_t sampleTime = frameTime;
925 if (mResampleTouch) {
926 sampleTime -= RESAMPLE_LATENCY;
927 }
Jeff Brown5912f952013-07-01 19:10:31 -0700928 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
929 if (split < 0) {
930 continue;
931 }
932
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800933 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700934 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500935 if (batch.samples.empty()) {
936 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700937 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700938 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500939 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700940 }
Michael Wright32232172013-10-21 12:05:22 -0700941 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700942 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
943 }
944 return result;
945 }
946
947 return WOULD_BLOCK;
948}
949
950status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800951 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700952 MotionEvent* motionEvent = factory->createMotionEvent();
953 if (! motionEvent) return NO_MEMORY;
954
955 uint32_t chain = 0;
956 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500957 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100958 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700959 if (i) {
960 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500961 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700962 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500963 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700964 addSample(motionEvent, &msg);
965 } else {
966 initializeMotionEvent(motionEvent, &msg);
967 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500968 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700969 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500970 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700971
972 *outSeq = chain;
973 *outEvent = motionEvent;
974 return OK;
975}
976
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100977void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800978 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700979 return;
980 }
981
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100982 int32_t deviceId = msg.body.motion.deviceId;
983 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700984
985 // Update the touch state history to incorporate the new input message.
986 // If the message is in the past relative to the most recently produced resampled
987 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100988 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700989 case AMOTION_EVENT_ACTION_DOWN: {
990 ssize_t index = findTouchState(deviceId, source);
991 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500992 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700993 index = mTouchStates.size() - 1;
994 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500995 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700996 touchState.initialize(deviceId, source);
997 touchState.addHistory(msg);
998 break;
999 }
1000
1001 case AMOTION_EVENT_ACTION_MOVE: {
1002 ssize_t index = findTouchState(deviceId, source);
1003 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001004 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001005 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001006 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001007 }
1008 break;
1009 }
1010
1011 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1012 ssize_t index = findTouchState(deviceId, source);
1013 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001014 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001015 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001016 rewriteMessage(touchState, msg);
1017 }
1018 break;
1019 }
1020
1021 case AMOTION_EVENT_ACTION_POINTER_UP: {
1022 ssize_t index = findTouchState(deviceId, source);
1023 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001025 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001026 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001027 }
1028 break;
1029 }
1030
1031 case AMOTION_EVENT_ACTION_SCROLL: {
1032 ssize_t index = findTouchState(deviceId, source);
1033 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001034 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001035 rewriteMessage(touchState, msg);
1036 }
1037 break;
1038 }
1039
1040 case AMOTION_EVENT_ACTION_UP:
1041 case AMOTION_EVENT_ACTION_CANCEL: {
1042 ssize_t index = findTouchState(deviceId, source);
1043 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001044 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001045 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001046 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001047 }
1048 break;
1049 }
1050 }
1051}
1052
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001053/**
1054 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1055 *
1056 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1057 * is in the past relative to msg and the past two events do not contain identical coordinates),
1058 * then invalidate the lastResample data for that pointer.
1059 * If the two past events have identical coordinates, then lastResample data for that pointer will
1060 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1061 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1062 * not equal to x0 is received.
1063 */
1064void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001065 nsecs_t eventTime = msg.body.motion.eventTime;
1066 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1067 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001068 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001069 if (eventTime < state.lastResample.eventTime ||
1070 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001071 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1072 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001073#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001074 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1075 resampleCoords.getX(), resampleCoords.getY(),
1076 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001077#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001078 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1079 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1080 } else {
1081 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001082 }
Jeff Brown5912f952013-07-01 19:10:31 -07001083 }
1084 }
1085}
1086
1087void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1088 const InputMessage* next) {
1089 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001090 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001091 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1092 return;
1093 }
1094
1095 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1096 if (index < 0) {
1097#if DEBUG_RESAMPLING
1098 ALOGD("Not resampled, no touch state for device.");
1099#endif
1100 return;
1101 }
1102
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001103 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001104 if (touchState.historySize < 1) {
1105#if DEBUG_RESAMPLING
1106 ALOGD("Not resampled, no history for device.");
1107#endif
1108 return;
1109 }
1110
1111 // Ensure that the current sample has all of the pointers that need to be reported.
1112 const History* current = touchState.getHistory(0);
1113 size_t pointerCount = event->getPointerCount();
1114 for (size_t i = 0; i < pointerCount; i++) {
1115 uint32_t id = event->getPointerId(i);
1116 if (!current->idBits.hasBit(id)) {
1117#if DEBUG_RESAMPLING
1118 ALOGD("Not resampled, missing id %d", id);
1119#endif
1120 return;
1121 }
1122 }
1123
1124 // Find the data to use for resampling.
1125 const History* other;
1126 History future;
1127 float alpha;
1128 if (next) {
1129 // Interpolate between current sample and future sample.
1130 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001131 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001132 other = &future;
1133 nsecs_t delta = future.eventTime - current->eventTime;
1134 if (delta < RESAMPLE_MIN_DELTA) {
1135#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001136 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001137#endif
1138 return;
1139 }
1140 alpha = float(sampleTime - current->eventTime) / delta;
1141 } else if (touchState.historySize >= 2) {
1142 // Extrapolate future sample using current sample and past sample.
1143 // So other->eventTime <= current->eventTime <= sampleTime.
1144 other = touchState.getHistory(1);
1145 nsecs_t delta = current->eventTime - other->eventTime;
1146 if (delta < RESAMPLE_MIN_DELTA) {
1147#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001148 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001149#endif
1150 return;
1151 } else if (delta > RESAMPLE_MAX_DELTA) {
1152#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001153 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001154#endif
1155 return;
1156 }
1157 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1158 if (sampleTime > maxPredict) {
1159#if DEBUG_RESAMPLING
1160 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001161 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001162 sampleTime - current->eventTime, maxPredict - current->eventTime);
1163#endif
1164 sampleTime = maxPredict;
1165 }
1166 alpha = float(current->eventTime - sampleTime) / delta;
1167 } else {
1168#if DEBUG_RESAMPLING
1169 ALOGD("Not resampled, insufficient data.");
1170#endif
1171 return;
1172 }
1173
1174 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001175 History oldLastResample;
1176 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001177 touchState.lastResample.eventTime = sampleTime;
1178 touchState.lastResample.idBits.clear();
1179 for (size_t i = 0; i < pointerCount; i++) {
1180 uint32_t id = event->getPointerId(i);
1181 touchState.lastResample.idToIndex[id] = i;
1182 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001183 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1184 // We maintain the previously resampled value for this pointer (stored in
1185 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1186 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1187
1188 // We know here that the coordinates for the pointer haven't changed because we
1189 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1190 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1191 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1192 continue;
1193 }
1194
Jeff Brown5912f952013-07-01 19:10:31 -07001195 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1196 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001197 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001198 if (other->idBits.hasBit(id)
1199 && shouldResampleTool(event->getToolType(i))) {
1200 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001201 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1202 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1203 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1204 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1205#if DEBUG_RESAMPLING
1206 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1207 "other (%0.3f, %0.3f), alpha %0.3f",
1208 id, resampledCoords.getX(), resampledCoords.getY(),
1209 currentCoords.getX(), currentCoords.getY(),
1210 otherCoords.getX(), otherCoords.getY(),
1211 alpha);
1212#endif
1213 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001214#if DEBUG_RESAMPLING
1215 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1216 id, resampledCoords.getX(), resampledCoords.getY(),
1217 currentCoords.getX(), currentCoords.getY());
1218#endif
1219 }
1220 }
1221
1222 event->addSample(sampleTime, touchState.lastResample.pointers);
1223}
1224
1225bool InputConsumer::shouldResampleTool(int32_t toolType) {
1226 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1227 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1228}
1229
1230status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001231 if (DEBUG_TRANSPORT_ACTIONS) {
1232 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1233 mChannel->getName().c_str(), seq, toString(handled));
1234 }
Jeff Brown5912f952013-07-01 19:10:31 -07001235
1236 if (!seq) {
1237 ALOGE("Attempted to send a finished signal with sequence number 0.");
1238 return BAD_VALUE;
1239 }
1240
1241 // Send finished signals for the batch sequence chain first.
1242 size_t seqChainCount = mSeqChains.size();
1243 if (seqChainCount) {
1244 uint32_t currentSeq = seq;
1245 uint32_t chainSeqs[seqChainCount];
1246 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001247 for (size_t i = seqChainCount; i > 0; ) {
1248 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001249 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001250 if (seqChain.seq == currentSeq) {
1251 currentSeq = seqChain.chain;
1252 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001253 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001254 }
1255 }
1256 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001257 while (!status && chainIndex > 0) {
1258 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001259 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1260 }
1261 if (status) {
1262 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001263 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001264 SeqChain seqChain;
1265 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1266 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001267 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001268 if (!chainIndex) break;
1269 chainIndex--;
1270 }
Jeff Brown5912f952013-07-01 19:10:31 -07001271 return status;
1272 }
1273 }
1274
1275 // Send finished signal for the last message in the batch.
1276 return sendUnchainedFinishedSignal(seq, handled);
1277}
1278
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001279status_t InputConsumer::sendTimeline(int32_t inputEventId,
1280 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1281 if (DEBUG_TRANSPORT_ACTIONS) {
1282 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1283 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1284 mChannel->getName().c_str(), inputEventId,
1285 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1286 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1287 }
1288
1289 InputMessage msg;
1290 msg.header.type = InputMessage::Type::TIMELINE;
1291 msg.header.seq = 0;
1292 msg.body.timeline.eventId = inputEventId;
1293 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1294 return mChannel->sendMessage(&msg);
1295}
1296
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001297nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1298 auto it = mConsumeTimes.find(seq);
1299 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1300 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1301 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1302 seq);
1303 return it->second;
1304}
1305
1306void InputConsumer::popConsumeTime(uint32_t seq) {
1307 mConsumeTimes.erase(seq);
1308}
1309
Jeff Brown5912f952013-07-01 19:10:31 -07001310status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1311 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001312 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001313 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001314 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001315 msg.body.finished.consumeTime = getConsumeTime(seq);
1316 status_t result = mChannel->sendMessage(&msg);
1317 if (result == OK) {
1318 // Remove the consume time if the socket write succeeded. We will not need to ack this
1319 // message anymore. If the socket write did not succeed, we will try again and will still
1320 // need consume time.
1321 popConsumeTime(seq);
1322 }
1323 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001324}
1325
1326bool InputConsumer::hasDeferredEvent() const {
1327 return mMsgDeferred;
1328}
1329
1330bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001331 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001332}
1333
Arthur Hungc7812be2020-02-27 22:40:27 +08001334int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001335 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001336 return AINPUT_SOURCE_CLASS_NONE;
1337 }
1338
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001339 const Batch& batch = mBatches[0];
1340 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001341 return head.body.motion.source;
1342}
1343
Jeff Brown5912f952013-07-01 19:10:31 -07001344ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1345 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001346 const Batch& batch = mBatches[i];
1347 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001348 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1349 return i;
1350 }
1351 }
1352 return -1;
1353}
1354
1355ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1356 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001357 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001358 if (touchState.deviceId == deviceId && touchState.source == source) {
1359 return i;
1360 }
1361 }
1362 return -1;
1363}
1364
1365void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001366 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001367 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1368 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1369 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1370 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001371}
1372
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001373void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001374 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1375 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001376}
1377
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001378void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001379 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001380}
1381
arthurhung7632c332020-12-30 16:58:01 +08001382void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1383 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1384 msg->body.drag.isExiting);
1385}
1386
Jeff Brown5912f952013-07-01 19:10:31 -07001387void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001388 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001389 PointerProperties pointerProperties[pointerCount];
1390 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001391 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001392 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1393 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1394 }
1395
chaviw9eaa22c2020-07-01 16:21:27 -07001396 ui::Transform transform;
1397 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1398 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001399 ui::Transform displayTransform;
1400 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1401 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1402 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001403 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1404 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1405 msg->body.motion.actionButton, msg->body.motion.flags,
1406 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001407 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1408 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1409 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001410 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1411 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001412}
1413
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001414void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1415 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1416}
1417
Jeff Brown5912f952013-07-01 19:10:31 -07001418void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001419 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001420 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001421 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001422 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1423 }
1424
1425 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1426 event->addSample(msg->body.motion.eventTime, pointerCoords);
1427}
1428
1429bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001430 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001431 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001432 if (head.body.motion.pointerCount != pointerCount
1433 || head.body.motion.action != msg->body.motion.action) {
1434 return false;
1435 }
1436 for (size_t i = 0; i < pointerCount; i++) {
1437 if (head.body.motion.pointers[i].properties
1438 != msg->body.motion.pointers[i].properties) {
1439 return false;
1440 }
1441 }
1442 return true;
1443}
1444
1445ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1446 size_t numSamples = batch.samples.size();
1447 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001448 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001449 index += 1;
1450 }
1451 return ssize_t(index) - 1;
1452}
1453
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001454std::string InputConsumer::dump() const {
1455 std::string out;
1456 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1457 out = out + "mChannel = " + mChannel->getName() + "\n";
1458 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1459 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001460 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001461 }
1462 out += "Batches:\n";
1463 for (const Batch& batch : mBatches) {
1464 out += " Batch:\n";
1465 for (const InputMessage& msg : batch.samples) {
1466 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001467 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001468 switch (msg.header.type) {
1469 case InputMessage::Type::KEY: {
1470 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1471 KeyEvent::actionToString(
1472 msg.body.key.action),
1473 msg.body.key.keyCode);
1474 break;
1475 }
1476 case InputMessage::Type::MOTION: {
1477 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1478 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1479 const float x = msg.body.motion.pointers[i].coords.getX();
1480 const float y = msg.body.motion.pointers[i].coords.getY();
1481 out += android::base::StringPrintf("\n Pointer %" PRIu32
1482 " : x=%.1f y=%.1f",
1483 i, x, y);
1484 }
1485 break;
1486 }
1487 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001488 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1489 toString(msg.body.finished.handled),
1490 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001491 break;
1492 }
1493 case InputMessage::Type::FOCUS: {
1494 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1495 toString(msg.body.focus.hasFocus),
1496 toString(msg.body.focus.inTouchMode));
1497 break;
1498 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001499 case InputMessage::Type::CAPTURE: {
1500 out += android::base::StringPrintf("hasCapture=%s",
1501 toString(msg.body.capture
1502 .pointerCaptureEnabled));
1503 break;
1504 }
arthurhung7632c332020-12-30 16:58:01 +08001505 case InputMessage::Type::DRAG: {
1506 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1507 msg.body.drag.x, msg.body.drag.y,
1508 toString(msg.body.drag.isExiting));
1509 break;
1510 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001511 case InputMessage::Type::TIMELINE: {
1512 const nsecs_t gpuCompletedTime =
1513 msg.body.timeline
1514 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1515 const nsecs_t presentTime =
1516 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1517 out += android::base::StringPrintf("inputEventId=%" PRId32
1518 ", gpuCompletedTime=%" PRId64
1519 ", presentTime=%" PRId64,
1520 msg.body.timeline.eventId, gpuCompletedTime,
1521 presentTime);
1522 break;
1523 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001524 case InputMessage::Type::TOUCH_MODE: {
1525 out += android::base::StringPrintf("isInTouchMode=%s",
1526 toString(msg.body.touchMode.isInTouchMode));
1527 break;
1528 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001529 }
1530 out += "\n";
1531 }
1532 }
1533 if (mBatches.empty()) {
1534 out += " <empty>\n";
1535 }
1536 out += "mSeqChains:\n";
1537 for (const SeqChain& chain : mSeqChains) {
1538 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1539 chain.chain);
1540 }
1541 if (mSeqChains.empty()) {
1542 out += " <empty>\n";
1543 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001544 out += "mConsumeTimes:\n";
1545 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1546 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1547 consumeTime);
1548 }
1549 if (mConsumeTimes.empty()) {
1550 out += " <empty>\n";
1551 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001552 return out;
1553}
1554
Jeff Brown5912f952013-07-01 19:10:31 -07001555} // namespace android