blob: 595c9d9ec0b3710e6936439e9d1c28d62ff85dbc [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>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
chaviw98318de2021-05-19 16:45:23 -050036#include <ftl/NamedEnum.h>
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 Rosky84f07f02021-04-16 10:42:42 -0700248 // int32_t displayW
249 msg->body.motion.displayWidth = body.motion.displayWidth;
250 // int32_t displayH
251 msg->body.motion.displayHeight = body.motion.displayHeight;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800252 // uint32_t pointerCount
253 msg->body.motion.pointerCount = body.motion.pointerCount;
254 //struct Pointer pointers[MAX_POINTERS]
255 for (size_t i = 0; i < body.motion.pointerCount; i++) {
256 // PointerProperties properties
257 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
258 msg->body.motion.pointers[i].properties.toolType =
259 body.motion.pointers[i].properties.toolType,
260 // PointerCoords coords
261 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
262 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
263 memcpy(&msg->body.motion.pointers[i].coords.values[0],
264 &body.motion.pointers[i].coords.values[0],
265 count * (sizeof(body.motion.pointers[i].coords.values[0])));
266 }
267 break;
268 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700269 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800270 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000271 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800272 break;
273 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800274 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800275 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800276 msg->body.focus.hasFocus = body.focus.hasFocus;
277 msg->body.focus.inTouchMode = body.focus.inTouchMode;
278 break;
279 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800280 case InputMessage::Type::CAPTURE: {
281 msg->body.capture.eventId = body.capture.eventId;
282 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
283 break;
284 }
arthurhung7632c332020-12-30 16:58:01 +0800285 case InputMessage::Type::DRAG: {
286 msg->body.drag.eventId = body.drag.eventId;
287 msg->body.drag.x = body.drag.x;
288 msg->body.drag.y = body.drag.y;
289 msg->body.drag.isExiting = body.drag.isExiting;
290 break;
291 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000292 case InputMessage::Type::TIMELINE: {
293 msg->body.timeline.eventId = body.timeline.eventId;
294 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
295 break;
296 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700297 case InputMessage::Type::TOUCH_MODE: {
298 msg->body.touchMode.eventId = body.touchMode.eventId;
299 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
300 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800301 }
302}
Jeff Brown5912f952013-07-01 19:10:31 -0700303
304// --- InputChannel ---
305
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500306std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500307 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700308 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
309 if (result != 0) {
310 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
311 strerror(errno));
312 return nullptr;
313 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500314 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500315 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700316}
317
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500318InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
319 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700320 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500321 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700322 }
Jeff Brown5912f952013-07-01 19:10:31 -0700323}
324
325InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700326 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500327 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700328 }
Robert Carr3720ed02018-08-08 16:08:27 -0700329}
330
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800331status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500332 std::unique_ptr<InputChannel>& outServerChannel,
333 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700334 int sockets[2];
335 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
336 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000337 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
338 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500339 outServerChannel.reset();
340 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700341 return result;
342 }
343
344 int bufferSize = SOCKET_BUFFER_SIZE;
345 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
346 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
347 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
348 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
349
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700350 sp<IBinder> token = new BBinder();
351
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700352 std::string serverChannelName = name + " (server)";
353 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700354 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700355
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700356 std::string clientChannelName = name + " (client)";
357 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700358 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700359 return OK;
360}
361
362status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800363 const size_t msgLength = msg->size();
364 InputMessage cleanMsg;
365 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700366 ssize_t nWrite;
367 do {
Chris Ye0783e992020-06-02 21:34:49 -0700368 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700369 } while (nWrite == -1 && errno == EINTR);
370
371 if (nWrite < 0) {
372 int error = errno;
373#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800374 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
375 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700376#endif
377 if (error == EAGAIN || error == EWOULDBLOCK) {
378 return WOULD_BLOCK;
379 }
380 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
381 return DEAD_OBJECT;
382 }
383 return -error;
384 }
385
386 if (size_t(nWrite) != msgLength) {
387#if DEBUG_CHANNEL_MESSAGES
388 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800389 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700390#endif
391 return DEAD_OBJECT;
392 }
393
394#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800395 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700396#endif
397 return OK;
398}
399
400status_t InputChannel::receiveMessage(InputMessage* msg) {
401 ssize_t nRead;
402 do {
Chris Ye0783e992020-06-02 21:34:49 -0700403 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700404 } while (nRead == -1 && errno == EINTR);
405
406 if (nRead < 0) {
407 int error = errno;
408#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800409 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700410#endif
411 if (error == EAGAIN || error == EWOULDBLOCK) {
412 return WOULD_BLOCK;
413 }
414 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
415 return DEAD_OBJECT;
416 }
417 return -error;
418 }
419
420 if (nRead == 0) { // check for EOF
421#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800422 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700423#endif
424 return DEAD_OBJECT;
425 }
426
427 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000428 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700429 return BAD_VALUE;
430 }
431
432#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800433 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700434#endif
435 return OK;
436}
437
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500438std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700439 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700440 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700441}
442
Garfield Tan15601662020-09-22 15:32:38 -0700443void InputChannel::copyTo(InputChannel& outChannel) const {
444 outChannel.mName = getName();
445 outChannel.mFd = dupFd();
446 outChannel.mToken = getConnectionToken();
447}
448
Chris Ye0783e992020-06-02 21:34:49 -0700449status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500450 if (parcel == nullptr) {
451 ALOGE("%s: Null parcel", __func__);
452 return BAD_VALUE;
453 }
454 return parcel->writeStrongBinder(mToken)
455 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700456}
457
Chris Ye0783e992020-06-02 21:34:49 -0700458status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500459 if (parcel == nullptr) {
460 ALOGE("%s: Null parcel", __func__);
461 return BAD_VALUE;
462 }
463 mToken = parcel->readStrongBinder();
464 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700465}
466
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700467sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500468 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700469}
470
Garfield Tan15601662020-09-22 15:32:38 -0700471base::unique_fd InputChannel::dupFd() const {
472 android::base::unique_fd newFd(::dup(getFd()));
473 if (!newFd.ok()) {
474 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
475 strerror(errno));
476 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
477 // If this process is out of file descriptors, then throwing that might end up exploding
478 // on the other side of a binder call, which isn't really helpful.
479 // Better to just crash here and hope that the FD leak is slow.
480 // Other failures could be client errors, so we still propagate those back to the caller.
481 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
482 getName().c_str());
483 return {};
484 }
485 return newFd;
486}
487
Jeff Brown5912f952013-07-01 19:10:31 -0700488// --- InputPublisher ---
489
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500490InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700491
492InputPublisher::~InputPublisher() {
493}
494
Garfield Tan1c7bc862020-01-28 13:24:04 -0800495status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
496 int32_t source, int32_t displayId,
497 std::array<uint8_t, 32> hmac, int32_t action,
498 int32_t flags, int32_t keyCode, int32_t scanCode,
499 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
500 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000501 if (ATRACE_ENABLED()) {
502 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
503 mChannel->getName().c_str(), keyCode);
504 ATRACE_NAME(message.c_str());
505 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800506 if (DEBUG_TRANSPORT_ACTIONS) {
507 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
508 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
509 "downTime=%" PRId64 ", eventTime=%" PRId64,
510 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
511 metaState, repeatCount, downTime, eventTime);
512 }
Jeff Brown5912f952013-07-01 19:10:31 -0700513
514 if (!seq) {
515 ALOGE("Attempted to publish a key event with sequence number 0.");
516 return BAD_VALUE;
517 }
518
519 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700520 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500521 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800522 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700523 msg.body.key.deviceId = deviceId;
524 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100525 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700526 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700527 msg.body.key.action = action;
528 msg.body.key.flags = flags;
529 msg.body.key.keyCode = keyCode;
530 msg.body.key.scanCode = scanCode;
531 msg.body.key.metaState = metaState;
532 msg.body.key.repeatCount = repeatCount;
533 msg.body.key.downTime = downTime;
534 msg.body.key.eventTime = eventTime;
535 return mChannel->sendMessage(&msg);
536}
537
538status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800539 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600540 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
541 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700542 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Evan Rosky84f07f02021-04-16 10:42:42 -0700543 float yPrecision, float xCursorPosition, float yCursorPosition, int32_t displayWidth,
544 int32_t displayHeight, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
545 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000546 if (ATRACE_ENABLED()) {
547 std::string message = StringPrintf(
548 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
549 mChannel->getName().c_str(), action);
550 ATRACE_NAME(message.c_str());
551 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800552 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700553 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700554 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800555 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
556 "displayId=%" PRId32 ", "
557 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700558 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800559 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700560 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800561 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
562 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700563 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
564 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800565 }
Jeff Brown5912f952013-07-01 19:10:31 -0700566
567 if (!seq) {
568 ALOGE("Attempted to publish a motion event with sequence number 0.");
569 return BAD_VALUE;
570 }
571
572 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700573 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800574 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700575 return BAD_VALUE;
576 }
577
578 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700579 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500580 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800581 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700582 msg.body.motion.deviceId = deviceId;
583 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700584 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700585 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700586 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100587 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700588 msg.body.motion.flags = flags;
589 msg.body.motion.edgeFlags = edgeFlags;
590 msg.body.motion.metaState = metaState;
591 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800592 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700593 msg.body.motion.dsdx = transform.dsdx();
594 msg.body.motion.dtdx = transform.dtdx();
595 msg.body.motion.dtdy = transform.dtdy();
596 msg.body.motion.dsdy = transform.dsdy();
597 msg.body.motion.tx = transform.tx();
598 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700599 msg.body.motion.xPrecision = xPrecision;
600 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700601 msg.body.motion.xCursorPosition = xCursorPosition;
602 msg.body.motion.yCursorPosition = yCursorPosition;
Evan Rosky84f07f02021-04-16 10:42:42 -0700603 msg.body.motion.displayWidth = displayWidth;
604 msg.body.motion.displayHeight = displayHeight;
Jeff Brown5912f952013-07-01 19:10:31 -0700605 msg.body.motion.downTime = downTime;
606 msg.body.motion.eventTime = eventTime;
607 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100608 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700609 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
610 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
611 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700612
Jeff Brown5912f952013-07-01 19:10:31 -0700613 return mChannel->sendMessage(&msg);
614}
615
Garfield Tan1c7bc862020-01-28 13:24:04 -0800616status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
617 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800618 if (ATRACE_ENABLED()) {
619 std::string message =
620 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
621 mChannel->getName().c_str(), toString(hasFocus),
622 toString(inTouchMode));
623 ATRACE_NAME(message.c_str());
624 }
625
626 InputMessage msg;
627 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500628 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800629 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000630 msg.body.focus.hasFocus = hasFocus;
631 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800632 return mChannel->sendMessage(&msg);
633}
634
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800635status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
636 bool pointerCaptureEnabled) {
637 if (ATRACE_ENABLED()) {
638 std::string message =
639 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
640 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
641 ATRACE_NAME(message.c_str());
642 }
643
644 InputMessage msg;
645 msg.header.type = InputMessage::Type::CAPTURE;
646 msg.header.seq = seq;
647 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000648 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800649 return mChannel->sendMessage(&msg);
650}
651
arthurhung7632c332020-12-30 16:58:01 +0800652status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
653 bool isExiting) {
654 if (ATRACE_ENABLED()) {
655 std::string message =
656 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
657 mChannel->getName().c_str(), x, y, toString(isExiting));
658 ATRACE_NAME(message.c_str());
659 }
660
661 InputMessage msg;
662 msg.header.type = InputMessage::Type::DRAG;
663 msg.header.seq = seq;
664 msg.body.drag.eventId = eventId;
665 msg.body.drag.isExiting = isExiting;
666 msg.body.drag.x = x;
667 msg.body.drag.y = y;
668 return mChannel->sendMessage(&msg);
669}
670
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700671status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
672 if (ATRACE_ENABLED()) {
673 std::string message =
674 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
675 mChannel->getName().c_str(), toString(isInTouchMode));
676 ATRACE_NAME(message.c_str());
677 }
678
679 InputMessage msg;
680 msg.header.type = InputMessage::Type::TOUCH_MODE;
681 msg.header.seq = seq;
682 msg.body.touchMode.eventId = eventId;
683 msg.body.touchMode.isInTouchMode = isInTouchMode;
684 return mChannel->sendMessage(&msg);
685}
686
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000687android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800688 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000689 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800690 }
Jeff Brown5912f952013-07-01 19:10:31 -0700691
692 InputMessage msg;
693 status_t result = mChannel->receiveMessage(&msg);
694 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000695 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700696 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000697 if (msg.header.type == InputMessage::Type::FINISHED) {
698 return Finished{
699 .seq = msg.header.seq,
700 .handled = msg.body.finished.handled,
701 .consumeTime = msg.body.finished.consumeTime,
702 };
Jeff Brown5912f952013-07-01 19:10:31 -0700703 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000704
705 if (msg.header.type == InputMessage::Type::TIMELINE) {
706 return Timeline{
707 .inputEventId = msg.body.timeline.eventId,
708 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
709 };
710 }
711
712 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
713 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
714 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700715}
716
717// --- InputConsumer ---
718
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500719InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
720 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700721
722InputConsumer::~InputConsumer() {
723}
724
725bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600726 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700727}
728
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800729status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
730 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800731 if (DEBUG_TRANSPORT_ACTIONS) {
732 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
733 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
734 }
Jeff Brown5912f952013-07-01 19:10:31 -0700735
736 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700737 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700738
739 // Fetch the next input message.
740 // Loop until an event can be returned or no additional events are received.
741 while (!*outEvent) {
742 if (mMsgDeferred) {
743 // mMsg contains a valid input message from the previous call to consume
744 // that has not yet been processed.
745 mMsgDeferred = false;
746 } else {
747 // Receive a fresh message.
748 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000749 if (result == OK) {
750 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
751 }
Jeff Brown5912f952013-07-01 19:10:31 -0700752 if (result) {
753 // Consume the next batched event unless batches are being held for later.
754 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800755 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700756 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800757 if (DEBUG_TRANSPORT_ACTIONS) {
758 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
759 mChannel->getName().c_str(), *outSeq);
760 }
Jeff Brown5912f952013-07-01 19:10:31 -0700761 break;
762 }
763 }
764 return result;
765 }
766 }
767
768 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700769 case InputMessage::Type::KEY: {
770 KeyEvent* keyEvent = factory->createKeyEvent();
771 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700772
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700773 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500774 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700775 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800776 if (DEBUG_TRANSPORT_ACTIONS) {
777 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
778 mChannel->getName().c_str(), *outSeq);
779 }
Jeff Brown5912f952013-07-01 19:10:31 -0700780 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700781 }
Jeff Brown5912f952013-07-01 19:10:31 -0700782
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700783 case InputMessage::Type::MOTION: {
784 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
785 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500786 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700787 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500788 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800789 if (DEBUG_TRANSPORT_ACTIONS) {
790 ALOGD("channel '%s' consumer ~ appended to batch event",
791 mChannel->getName().c_str());
792 }
Jeff Brown5912f952013-07-01 19:10:31 -0700793 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700794 } else if (isPointerEvent(mMsg.body.motion.source) &&
795 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
796 // No need to process events that we are going to cancel anyways
797 const size_t count = batch.samples.size();
798 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500799 const InputMessage& msg = batch.samples[i];
800 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700801 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500802 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
803 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700804 } else {
805 // We cannot append to the batch in progress, so we need to consume
806 // the previous batch right now and defer the new message until later.
807 mMsgDeferred = true;
808 status_t result = consumeSamples(factory, batch, batch.samples.size(),
809 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500810 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700811 if (result) {
812 return result;
813 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800814 if (DEBUG_TRANSPORT_ACTIONS) {
815 ALOGD("channel '%s' consumer ~ consumed batch event and "
816 "deferred current event, seq=%u",
817 mChannel->getName().c_str(), *outSeq);
818 }
Jeff Brown5912f952013-07-01 19:10:31 -0700819 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700820 }
Jeff Brown5912f952013-07-01 19:10:31 -0700821 }
Jeff Brown5912f952013-07-01 19:10:31 -0700822
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800823 // Start a new batch if needed.
824 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
825 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500826 Batch batch;
827 batch.samples.push_back(mMsg);
828 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800829 if (DEBUG_TRANSPORT_ACTIONS) {
830 ALOGD("channel '%s' consumer ~ started batch event",
831 mChannel->getName().c_str());
832 }
833 break;
834 }
Jeff Brown5912f952013-07-01 19:10:31 -0700835
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800836 MotionEvent* motionEvent = factory->createMotionEvent();
837 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700838
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800839 updateTouchState(mMsg);
840 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500841 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800842 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800843
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800844 if (DEBUG_TRANSPORT_ACTIONS) {
845 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
846 mChannel->getName().c_str(), *outSeq);
847 }
848 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700849 }
Jeff Brown5912f952013-07-01 19:10:31 -0700850
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000851 case InputMessage::Type::FINISHED:
852 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000853 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
854 "InputConsumer!",
855 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800856 break;
857 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800858
859 case InputMessage::Type::FOCUS: {
860 FocusEvent* focusEvent = factory->createFocusEvent();
861 if (!focusEvent) return NO_MEMORY;
862
863 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500864 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800865 *outEvent = focusEvent;
866 break;
867 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800868
869 case InputMessage::Type::CAPTURE: {
870 CaptureEvent* captureEvent = factory->createCaptureEvent();
871 if (!captureEvent) return NO_MEMORY;
872
873 initializeCaptureEvent(captureEvent, &mMsg);
874 *outSeq = mMsg.header.seq;
875 *outEvent = captureEvent;
876 break;
877 }
arthurhung7632c332020-12-30 16:58:01 +0800878
879 case InputMessage::Type::DRAG: {
880 DragEvent* dragEvent = factory->createDragEvent();
881 if (!dragEvent) return NO_MEMORY;
882
883 initializeDragEvent(dragEvent, &mMsg);
884 *outSeq = mMsg.header.seq;
885 *outEvent = dragEvent;
886 break;
887 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700888
889 case InputMessage::Type::TOUCH_MODE: {
890 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
891 if (!touchModeEvent) return NO_MEMORY;
892
893 initializeTouchModeEvent(touchModeEvent, &mMsg);
894 *outSeq = mMsg.header.seq;
895 *outEvent = touchModeEvent;
896 break;
897 }
Jeff Brown5912f952013-07-01 19:10:31 -0700898 }
899 }
900 return OK;
901}
902
903status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800904 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700905 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700906 for (size_t i = mBatches.size(); i > 0; ) {
907 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500908 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700909 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800910 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500911 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700912 return result;
913 }
914
Michael Wright32232172013-10-21 12:05:22 -0700915 nsecs_t sampleTime = frameTime;
916 if (mResampleTouch) {
917 sampleTime -= RESAMPLE_LATENCY;
918 }
Jeff Brown5912f952013-07-01 19:10:31 -0700919 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
920 if (split < 0) {
921 continue;
922 }
923
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800924 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700925 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500926 if (batch.samples.empty()) {
927 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700928 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700929 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500930 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700931 }
Michael Wright32232172013-10-21 12:05:22 -0700932 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700933 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
934 }
935 return result;
936 }
937
938 return WOULD_BLOCK;
939}
940
941status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800942 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700943 MotionEvent* motionEvent = factory->createMotionEvent();
944 if (! motionEvent) return NO_MEMORY;
945
946 uint32_t chain = 0;
947 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500948 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100949 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700950 if (i) {
951 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500952 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700953 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500954 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700955 addSample(motionEvent, &msg);
956 } else {
957 initializeMotionEvent(motionEvent, &msg);
958 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500959 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700960 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500961 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700962
963 *outSeq = chain;
964 *outEvent = motionEvent;
965 return OK;
966}
967
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100968void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800969 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700970 return;
971 }
972
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100973 int32_t deviceId = msg.body.motion.deviceId;
974 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700975
976 // Update the touch state history to incorporate the new input message.
977 // If the message is in the past relative to the most recently produced resampled
978 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100979 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700980 case AMOTION_EVENT_ACTION_DOWN: {
981 ssize_t index = findTouchState(deviceId, source);
982 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500983 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700984 index = mTouchStates.size() - 1;
985 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500986 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700987 touchState.initialize(deviceId, source);
988 touchState.addHistory(msg);
989 break;
990 }
991
992 case AMOTION_EVENT_ACTION_MOVE: {
993 ssize_t index = findTouchState(deviceId, source);
994 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500995 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700996 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800997 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700998 }
999 break;
1000 }
1001
1002 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1003 ssize_t index = findTouchState(deviceId, source);
1004 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001005 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001006 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001007 rewriteMessage(touchState, msg);
1008 }
1009 break;
1010 }
1011
1012 case AMOTION_EVENT_ACTION_POINTER_UP: {
1013 ssize_t index = findTouchState(deviceId, source);
1014 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001015 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001016 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001017 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001018 }
1019 break;
1020 }
1021
1022 case AMOTION_EVENT_ACTION_SCROLL: {
1023 ssize_t index = findTouchState(deviceId, source);
1024 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001025 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001026 rewriteMessage(touchState, msg);
1027 }
1028 break;
1029 }
1030
1031 case AMOTION_EVENT_ACTION_UP:
1032 case AMOTION_EVENT_ACTION_CANCEL: {
1033 ssize_t index = findTouchState(deviceId, source);
1034 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001035 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001036 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001037 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001038 }
1039 break;
1040 }
1041 }
1042}
1043
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001044/**
1045 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1046 *
1047 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1048 * is in the past relative to msg and the past two events do not contain identical coordinates),
1049 * then invalidate the lastResample data for that pointer.
1050 * If the two past events have identical coordinates, then lastResample data for that pointer will
1051 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1052 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1053 * not equal to x0 is received.
1054 */
1055void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001056 nsecs_t eventTime = msg.body.motion.eventTime;
1057 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1058 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001059 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001060 if (eventTime < state.lastResample.eventTime ||
1061 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001062 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1063 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001064#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001065 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1066 resampleCoords.getX(), resampleCoords.getY(),
1067 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001068#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001069 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1070 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1071 } else {
1072 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001073 }
Jeff Brown5912f952013-07-01 19:10:31 -07001074 }
1075 }
1076}
1077
1078void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1079 const InputMessage* next) {
1080 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001081 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001082 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1083 return;
1084 }
1085
1086 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1087 if (index < 0) {
1088#if DEBUG_RESAMPLING
1089 ALOGD("Not resampled, no touch state for device.");
1090#endif
1091 return;
1092 }
1093
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001094 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001095 if (touchState.historySize < 1) {
1096#if DEBUG_RESAMPLING
1097 ALOGD("Not resampled, no history for device.");
1098#endif
1099 return;
1100 }
1101
1102 // Ensure that the current sample has all of the pointers that need to be reported.
1103 const History* current = touchState.getHistory(0);
1104 size_t pointerCount = event->getPointerCount();
1105 for (size_t i = 0; i < pointerCount; i++) {
1106 uint32_t id = event->getPointerId(i);
1107 if (!current->idBits.hasBit(id)) {
1108#if DEBUG_RESAMPLING
1109 ALOGD("Not resampled, missing id %d", id);
1110#endif
1111 return;
1112 }
1113 }
1114
1115 // Find the data to use for resampling.
1116 const History* other;
1117 History future;
1118 float alpha;
1119 if (next) {
1120 // Interpolate between current sample and future sample.
1121 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001122 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001123 other = &future;
1124 nsecs_t delta = future.eventTime - current->eventTime;
1125 if (delta < RESAMPLE_MIN_DELTA) {
1126#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001127 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001128#endif
1129 return;
1130 }
1131 alpha = float(sampleTime - current->eventTime) / delta;
1132 } else if (touchState.historySize >= 2) {
1133 // Extrapolate future sample using current sample and past sample.
1134 // So other->eventTime <= current->eventTime <= sampleTime.
1135 other = touchState.getHistory(1);
1136 nsecs_t delta = current->eventTime - other->eventTime;
1137 if (delta < RESAMPLE_MIN_DELTA) {
1138#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001139 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001140#endif
1141 return;
1142 } else if (delta > RESAMPLE_MAX_DELTA) {
1143#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001144 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001145#endif
1146 return;
1147 }
1148 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1149 if (sampleTime > maxPredict) {
1150#if DEBUG_RESAMPLING
1151 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001152 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001153 sampleTime - current->eventTime, maxPredict - current->eventTime);
1154#endif
1155 sampleTime = maxPredict;
1156 }
1157 alpha = float(current->eventTime - sampleTime) / delta;
1158 } else {
1159#if DEBUG_RESAMPLING
1160 ALOGD("Not resampled, insufficient data.");
1161#endif
1162 return;
1163 }
1164
1165 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001166 History oldLastResample;
1167 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001168 touchState.lastResample.eventTime = sampleTime;
1169 touchState.lastResample.idBits.clear();
1170 for (size_t i = 0; i < pointerCount; i++) {
1171 uint32_t id = event->getPointerId(i);
1172 touchState.lastResample.idToIndex[id] = i;
1173 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001174 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1175 // We maintain the previously resampled value for this pointer (stored in
1176 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1177 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1178
1179 // We know here that the coordinates for the pointer haven't changed because we
1180 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1181 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1182 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1183 continue;
1184 }
1185
Jeff Brown5912f952013-07-01 19:10:31 -07001186 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1187 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001188 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001189 if (other->idBits.hasBit(id)
1190 && shouldResampleTool(event->getToolType(i))) {
1191 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001192 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1193 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1194 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1195 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1196#if DEBUG_RESAMPLING
1197 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1198 "other (%0.3f, %0.3f), alpha %0.3f",
1199 id, resampledCoords.getX(), resampledCoords.getY(),
1200 currentCoords.getX(), currentCoords.getY(),
1201 otherCoords.getX(), otherCoords.getY(),
1202 alpha);
1203#endif
1204 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001205#if DEBUG_RESAMPLING
1206 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1207 id, resampledCoords.getX(), resampledCoords.getY(),
1208 currentCoords.getX(), currentCoords.getY());
1209#endif
1210 }
1211 }
1212
1213 event->addSample(sampleTime, touchState.lastResample.pointers);
1214}
1215
1216bool InputConsumer::shouldResampleTool(int32_t toolType) {
1217 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1218 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1219}
1220
1221status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001222 if (DEBUG_TRANSPORT_ACTIONS) {
1223 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1224 mChannel->getName().c_str(), seq, toString(handled));
1225 }
Jeff Brown5912f952013-07-01 19:10:31 -07001226
1227 if (!seq) {
1228 ALOGE("Attempted to send a finished signal with sequence number 0.");
1229 return BAD_VALUE;
1230 }
1231
1232 // Send finished signals for the batch sequence chain first.
1233 size_t seqChainCount = mSeqChains.size();
1234 if (seqChainCount) {
1235 uint32_t currentSeq = seq;
1236 uint32_t chainSeqs[seqChainCount];
1237 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001238 for (size_t i = seqChainCount; i > 0; ) {
1239 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001240 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001241 if (seqChain.seq == currentSeq) {
1242 currentSeq = seqChain.chain;
1243 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001244 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001245 }
1246 }
1247 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001248 while (!status && chainIndex > 0) {
1249 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001250 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1251 }
1252 if (status) {
1253 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001254 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001255 SeqChain seqChain;
1256 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1257 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001258 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001259 if (!chainIndex) break;
1260 chainIndex--;
1261 }
Jeff Brown5912f952013-07-01 19:10:31 -07001262 return status;
1263 }
1264 }
1265
1266 // Send finished signal for the last message in the batch.
1267 return sendUnchainedFinishedSignal(seq, handled);
1268}
1269
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001270status_t InputConsumer::sendTimeline(int32_t inputEventId,
1271 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1272 if (DEBUG_TRANSPORT_ACTIONS) {
1273 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1274 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1275 mChannel->getName().c_str(), inputEventId,
1276 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1277 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1278 }
1279
1280 InputMessage msg;
1281 msg.header.type = InputMessage::Type::TIMELINE;
1282 msg.header.seq = 0;
1283 msg.body.timeline.eventId = inputEventId;
1284 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1285 return mChannel->sendMessage(&msg);
1286}
1287
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001288nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1289 auto it = mConsumeTimes.find(seq);
1290 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1291 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1292 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1293 seq);
1294 return it->second;
1295}
1296
1297void InputConsumer::popConsumeTime(uint32_t seq) {
1298 mConsumeTimes.erase(seq);
1299}
1300
Jeff Brown5912f952013-07-01 19:10:31 -07001301status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1302 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001303 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001304 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001305 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001306 msg.body.finished.consumeTime = getConsumeTime(seq);
1307 status_t result = mChannel->sendMessage(&msg);
1308 if (result == OK) {
1309 // Remove the consume time if the socket write succeeded. We will not need to ack this
1310 // message anymore. If the socket write did not succeed, we will try again and will still
1311 // need consume time.
1312 popConsumeTime(seq);
1313 }
1314 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001315}
1316
1317bool InputConsumer::hasDeferredEvent() const {
1318 return mMsgDeferred;
1319}
1320
1321bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001322 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001323}
1324
Arthur Hungc7812be2020-02-27 22:40:27 +08001325int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001326 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001327 return AINPUT_SOURCE_CLASS_NONE;
1328 }
1329
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001330 const Batch& batch = mBatches[0];
1331 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001332 return head.body.motion.source;
1333}
1334
Jeff Brown5912f952013-07-01 19:10:31 -07001335ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1336 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001337 const Batch& batch = mBatches[i];
1338 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001339 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1340 return i;
1341 }
1342 }
1343 return -1;
1344}
1345
1346ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1347 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001348 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001349 if (touchState.deviceId == deviceId && touchState.source == source) {
1350 return i;
1351 }
1352 }
1353 return -1;
1354}
1355
1356void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001357 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001358 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1359 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1360 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1361 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001362}
1363
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001364void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001365 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1366 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001367}
1368
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001369void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001370 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001371}
1372
arthurhung7632c332020-12-30 16:58:01 +08001373void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1374 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1375 msg->body.drag.isExiting);
1376}
1377
Jeff Brown5912f952013-07-01 19:10:31 -07001378void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001379 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001380 PointerProperties pointerProperties[pointerCount];
1381 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001382 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001383 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1384 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1385 }
1386
chaviw9eaa22c2020-07-01 16:21:27 -07001387 ui::Transform transform;
1388 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1389 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001390 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1391 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1392 msg->body.motion.actionButton, msg->body.motion.flags,
1393 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001394 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1395 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1396 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07001397 msg->body.motion.displayWidth, msg->body.motion.displayHeight,
chaviw9eaa22c2020-07-01 16:21:27 -07001398 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1399 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001400}
1401
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001402void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1403 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1404}
1405
Jeff Brown5912f952013-07-01 19:10:31 -07001406void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001407 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001408 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001409 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001410 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1411 }
1412
1413 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1414 event->addSample(msg->body.motion.eventTime, pointerCoords);
1415}
1416
1417bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001418 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001419 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001420 if (head.body.motion.pointerCount != pointerCount
1421 || head.body.motion.action != msg->body.motion.action) {
1422 return false;
1423 }
1424 for (size_t i = 0; i < pointerCount; i++) {
1425 if (head.body.motion.pointers[i].properties
1426 != msg->body.motion.pointers[i].properties) {
1427 return false;
1428 }
1429 }
1430 return true;
1431}
1432
1433ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1434 size_t numSamples = batch.samples.size();
1435 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001436 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001437 index += 1;
1438 }
1439 return ssize_t(index) - 1;
1440}
1441
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001442std::string InputConsumer::dump() const {
1443 std::string out;
1444 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1445 out = out + "mChannel = " + mChannel->getName() + "\n";
1446 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1447 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001448 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001449 }
1450 out += "Batches:\n";
1451 for (const Batch& batch : mBatches) {
1452 out += " Batch:\n";
1453 for (const InputMessage& msg : batch.samples) {
1454 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001455 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001456 switch (msg.header.type) {
1457 case InputMessage::Type::KEY: {
1458 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1459 KeyEvent::actionToString(
1460 msg.body.key.action),
1461 msg.body.key.keyCode);
1462 break;
1463 }
1464 case InputMessage::Type::MOTION: {
1465 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1466 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1467 const float x = msg.body.motion.pointers[i].coords.getX();
1468 const float y = msg.body.motion.pointers[i].coords.getY();
1469 out += android::base::StringPrintf("\n Pointer %" PRIu32
1470 " : x=%.1f y=%.1f",
1471 i, x, y);
1472 }
1473 break;
1474 }
1475 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001476 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1477 toString(msg.body.finished.handled),
1478 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001479 break;
1480 }
1481 case InputMessage::Type::FOCUS: {
1482 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1483 toString(msg.body.focus.hasFocus),
1484 toString(msg.body.focus.inTouchMode));
1485 break;
1486 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001487 case InputMessage::Type::CAPTURE: {
1488 out += android::base::StringPrintf("hasCapture=%s",
1489 toString(msg.body.capture
1490 .pointerCaptureEnabled));
1491 break;
1492 }
arthurhung7632c332020-12-30 16:58:01 +08001493 case InputMessage::Type::DRAG: {
1494 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1495 msg.body.drag.x, msg.body.drag.y,
1496 toString(msg.body.drag.isExiting));
1497 break;
1498 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001499 case InputMessage::Type::TIMELINE: {
1500 const nsecs_t gpuCompletedTime =
1501 msg.body.timeline
1502 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1503 const nsecs_t presentTime =
1504 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1505 out += android::base::StringPrintf("inputEventId=%" PRId32
1506 ", gpuCompletedTime=%" PRId64
1507 ", presentTime=%" PRId64,
1508 msg.body.timeline.eventId, gpuCompletedTime,
1509 presentTime);
1510 break;
1511 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001512 case InputMessage::Type::TOUCH_MODE: {
1513 out += android::base::StringPrintf("isInTouchMode=%s",
1514 toString(msg.body.touchMode.isInTouchMode));
1515 break;
1516 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001517 }
1518 out += "\n";
1519 }
1520 }
1521 if (mBatches.empty()) {
1522 out += " <empty>\n";
1523 }
1524 out += "mSeqChains:\n";
1525 for (const SeqChain& chain : mSeqChains) {
1526 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1527 chain.chain);
1528 }
1529 if (mSeqChains.empty()) {
1530 out += " <empty>\n";
1531 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001532 out += "mConsumeTimes:\n";
1533 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1534 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1535 consumeTime);
1536 }
1537 if (mConsumeTimes.empty()) {
1538 out += " <empty>\n";
1539 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001540 return out;
1541}
1542
Jeff Brown5912f952013-07-01 19:10:31 -07001543} // namespace android