blob: d6c1161509892871cc03ffd50c82d3e00b916f03 [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
chaviw3277faf2021-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:
119 return true;
120 case Type::TIMELINE: {
121 const nsecs_t gpuCompletedTime =
122 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
123 const nsecs_t presentTime =
124 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
125 const bool valid = presentTime > gpuCompletedTime;
126 if (!valid) {
127 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
128 " presentTime = %" PRId64,
129 gpuCompletedTime, presentTime);
130 }
131 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700132 }
133 }
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000134 ALOGE("Invalid message type: %" PRIu32, header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700135 return false;
136}
137
138size_t InputMessage::size() const {
139 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700140 case Type::KEY:
141 return sizeof(Header) + body.key.size();
142 case Type::MOTION:
143 return sizeof(Header) + body.motion.size();
144 case Type::FINISHED:
145 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800146 case Type::FOCUS:
147 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800148 case Type::CAPTURE:
149 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800150 case Type::DRAG:
151 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000152 case Type::TIMELINE:
153 return sizeof(Header) + body.timeline.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700154 }
155 return sizeof(Header);
156}
157
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800158/**
159 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
160 * memory to zero, then only copy the valid bytes on a per-field basis.
161 */
162void InputMessage::getSanitizedCopy(InputMessage* msg) const {
163 memset(msg, 0, sizeof(*msg));
164
165 // Write the header
166 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500167 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800168
169 // Write the body
170 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700171 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800172 // int32_t eventId
173 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800174 // nsecs_t eventTime
175 msg->body.key.eventTime = body.key.eventTime;
176 // int32_t deviceId
177 msg->body.key.deviceId = body.key.deviceId;
178 // int32_t source
179 msg->body.key.source = body.key.source;
180 // int32_t displayId
181 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600182 // std::array<uint8_t, 32> hmac
183 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800184 // int32_t action
185 msg->body.key.action = body.key.action;
186 // int32_t flags
187 msg->body.key.flags = body.key.flags;
188 // int32_t keyCode
189 msg->body.key.keyCode = body.key.keyCode;
190 // int32_t scanCode
191 msg->body.key.scanCode = body.key.scanCode;
192 // int32_t metaState
193 msg->body.key.metaState = body.key.metaState;
194 // int32_t repeatCount
195 msg->body.key.repeatCount = body.key.repeatCount;
196 // nsecs_t downTime
197 msg->body.key.downTime = body.key.downTime;
198 break;
199 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700200 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800201 // int32_t eventId
202 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800203 // nsecs_t eventTime
204 msg->body.motion.eventTime = body.motion.eventTime;
205 // int32_t deviceId
206 msg->body.motion.deviceId = body.motion.deviceId;
207 // int32_t source
208 msg->body.motion.source = body.motion.source;
209 // int32_t displayId
210 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600211 // std::array<uint8_t, 32> hmac
212 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800213 // int32_t action
214 msg->body.motion.action = body.motion.action;
215 // int32_t actionButton
216 msg->body.motion.actionButton = body.motion.actionButton;
217 // int32_t flags
218 msg->body.motion.flags = body.motion.flags;
219 // int32_t metaState
220 msg->body.motion.metaState = body.motion.metaState;
221 // int32_t buttonState
222 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800223 // MotionClassification classification
224 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800225 // int32_t edgeFlags
226 msg->body.motion.edgeFlags = body.motion.edgeFlags;
227 // nsecs_t downTime
228 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700229
230 msg->body.motion.dsdx = body.motion.dsdx;
231 msg->body.motion.dtdx = body.motion.dtdx;
232 msg->body.motion.dtdy = body.motion.dtdy;
233 msg->body.motion.dsdy = body.motion.dsdy;
234 msg->body.motion.tx = body.motion.tx;
235 msg->body.motion.ty = body.motion.ty;
236
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800237 // float xPrecision
238 msg->body.motion.xPrecision = body.motion.xPrecision;
239 // float yPrecision
240 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700241 // float xCursorPosition
242 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
243 // float yCursorPosition
244 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Evan Rosky84f07f02021-04-16 10:42:42 -0700245 // int32_t displayW
246 msg->body.motion.displayWidth = body.motion.displayWidth;
247 // int32_t displayH
248 msg->body.motion.displayHeight = body.motion.displayHeight;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800249 // uint32_t pointerCount
250 msg->body.motion.pointerCount = body.motion.pointerCount;
251 //struct Pointer pointers[MAX_POINTERS]
252 for (size_t i = 0; i < body.motion.pointerCount; i++) {
253 // PointerProperties properties
254 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
255 msg->body.motion.pointers[i].properties.toolType =
256 body.motion.pointers[i].properties.toolType,
257 // PointerCoords coords
258 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
259 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
260 memcpy(&msg->body.motion.pointers[i].coords.values[0],
261 &body.motion.pointers[i].coords.values[0],
262 count * (sizeof(body.motion.pointers[i].coords.values[0])));
263 }
264 break;
265 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700266 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800267 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000268 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800269 break;
270 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800271 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800272 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800273 msg->body.focus.hasFocus = body.focus.hasFocus;
274 msg->body.focus.inTouchMode = body.focus.inTouchMode;
275 break;
276 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800277 case InputMessage::Type::CAPTURE: {
278 msg->body.capture.eventId = body.capture.eventId;
279 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
280 break;
281 }
arthurhung7632c332020-12-30 16:58:01 +0800282 case InputMessage::Type::DRAG: {
283 msg->body.drag.eventId = body.drag.eventId;
284 msg->body.drag.x = body.drag.x;
285 msg->body.drag.y = body.drag.y;
286 msg->body.drag.isExiting = body.drag.isExiting;
287 break;
288 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000289 case InputMessage::Type::TIMELINE: {
290 msg->body.timeline.eventId = body.timeline.eventId;
291 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
292 break;
293 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800294 }
295}
Jeff Brown5912f952013-07-01 19:10:31 -0700296
297// --- InputChannel ---
298
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500299std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500300 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700301 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
302 if (result != 0) {
303 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
304 strerror(errno));
305 return nullptr;
306 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500307 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500308 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700309}
310
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500311InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
312 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700313 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500314 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700315 }
Jeff Brown5912f952013-07-01 19:10:31 -0700316}
317
318InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700319 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500320 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700321 }
Robert Carr3720ed02018-08-08 16:08:27 -0700322}
323
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800324status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500325 std::unique_ptr<InputChannel>& outServerChannel,
326 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700327 int sockets[2];
328 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
329 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000330 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
331 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500332 outServerChannel.reset();
333 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700334 return result;
335 }
336
337 int bufferSize = SOCKET_BUFFER_SIZE;
338 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
339 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
340 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
341 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
342
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700343 sp<IBinder> token = new BBinder();
344
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700345 std::string serverChannelName = name + " (server)";
346 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700347 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700348
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700349 std::string clientChannelName = name + " (client)";
350 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700351 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700352 return OK;
353}
354
355status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800356 const size_t msgLength = msg->size();
357 InputMessage cleanMsg;
358 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700359 ssize_t nWrite;
360 do {
Chris Ye0783e992020-06-02 21:34:49 -0700361 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700362 } while (nWrite == -1 && errno == EINTR);
363
364 if (nWrite < 0) {
365 int error = errno;
366#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800367 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
368 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700369#endif
370 if (error == EAGAIN || error == EWOULDBLOCK) {
371 return WOULD_BLOCK;
372 }
373 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
374 return DEAD_OBJECT;
375 }
376 return -error;
377 }
378
379 if (size_t(nWrite) != msgLength) {
380#if DEBUG_CHANNEL_MESSAGES
381 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800382 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700383#endif
384 return DEAD_OBJECT;
385 }
386
387#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800388 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700389#endif
390 return OK;
391}
392
393status_t InputChannel::receiveMessage(InputMessage* msg) {
394 ssize_t nRead;
395 do {
Chris Ye0783e992020-06-02 21:34:49 -0700396 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700397 } while (nRead == -1 && errno == EINTR);
398
399 if (nRead < 0) {
400 int error = errno;
401#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800402 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700403#endif
404 if (error == EAGAIN || error == EWOULDBLOCK) {
405 return WOULD_BLOCK;
406 }
407 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
408 return DEAD_OBJECT;
409 }
410 return -error;
411 }
412
413 if (nRead == 0) { // check for EOF
414#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800415 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700416#endif
417 return DEAD_OBJECT;
418 }
419
420 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000421 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700422 return BAD_VALUE;
423 }
424
425#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800426 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700427#endif
428 return OK;
429}
430
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500431std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700432 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700433 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700434}
435
Garfield Tan15601662020-09-22 15:32:38 -0700436void InputChannel::copyTo(InputChannel& outChannel) const {
437 outChannel.mName = getName();
438 outChannel.mFd = dupFd();
439 outChannel.mToken = getConnectionToken();
440}
441
Chris Ye0783e992020-06-02 21:34:49 -0700442status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500443 if (parcel == nullptr) {
444 ALOGE("%s: Null parcel", __func__);
445 return BAD_VALUE;
446 }
447 return parcel->writeStrongBinder(mToken)
448 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700449}
450
Chris Ye0783e992020-06-02 21:34:49 -0700451status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500452 if (parcel == nullptr) {
453 ALOGE("%s: Null parcel", __func__);
454 return BAD_VALUE;
455 }
456 mToken = parcel->readStrongBinder();
457 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700458}
459
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700460sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500461 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700462}
463
Garfield Tan15601662020-09-22 15:32:38 -0700464base::unique_fd InputChannel::dupFd() const {
465 android::base::unique_fd newFd(::dup(getFd()));
466 if (!newFd.ok()) {
467 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
468 strerror(errno));
469 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
470 // If this process is out of file descriptors, then throwing that might end up exploding
471 // on the other side of a binder call, which isn't really helpful.
472 // Better to just crash here and hope that the FD leak is slow.
473 // Other failures could be client errors, so we still propagate those back to the caller.
474 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
475 getName().c_str());
476 return {};
477 }
478 return newFd;
479}
480
Jeff Brown5912f952013-07-01 19:10:31 -0700481// --- InputPublisher ---
482
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500483InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700484
485InputPublisher::~InputPublisher() {
486}
487
Garfield Tan1c7bc862020-01-28 13:24:04 -0800488status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
489 int32_t source, int32_t displayId,
490 std::array<uint8_t, 32> hmac, int32_t action,
491 int32_t flags, int32_t keyCode, int32_t scanCode,
492 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
493 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000494 if (ATRACE_ENABLED()) {
495 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
496 mChannel->getName().c_str(), keyCode);
497 ATRACE_NAME(message.c_str());
498 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800499 if (DEBUG_TRANSPORT_ACTIONS) {
500 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
501 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
502 "downTime=%" PRId64 ", eventTime=%" PRId64,
503 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
504 metaState, repeatCount, downTime, eventTime);
505 }
Jeff Brown5912f952013-07-01 19:10:31 -0700506
507 if (!seq) {
508 ALOGE("Attempted to publish a key event with sequence number 0.");
509 return BAD_VALUE;
510 }
511
512 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700513 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500514 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800515 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700516 msg.body.key.deviceId = deviceId;
517 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100518 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700519 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700520 msg.body.key.action = action;
521 msg.body.key.flags = flags;
522 msg.body.key.keyCode = keyCode;
523 msg.body.key.scanCode = scanCode;
524 msg.body.key.metaState = metaState;
525 msg.body.key.repeatCount = repeatCount;
526 msg.body.key.downTime = downTime;
527 msg.body.key.eventTime = eventTime;
528 return mChannel->sendMessage(&msg);
529}
530
531status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800532 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600533 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
534 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700535 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Evan Rosky84f07f02021-04-16 10:42:42 -0700536 float yPrecision, float xCursorPosition, float yCursorPosition, int32_t displayWidth,
537 int32_t displayHeight, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
538 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000539 if (ATRACE_ENABLED()) {
540 std::string message = StringPrintf(
541 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
542 mChannel->getName().c_str(), action);
543 ATRACE_NAME(message.c_str());
544 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800545 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700546 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700547 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800548 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
549 "displayId=%" PRId32 ", "
550 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700551 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800552 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700553 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800554 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
555 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700556 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
557 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800558 }
Jeff Brown5912f952013-07-01 19:10:31 -0700559
560 if (!seq) {
561 ALOGE("Attempted to publish a motion event with sequence number 0.");
562 return BAD_VALUE;
563 }
564
565 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700566 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800567 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700568 return BAD_VALUE;
569 }
570
571 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700572 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500573 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800574 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700575 msg.body.motion.deviceId = deviceId;
576 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700577 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700578 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700579 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100580 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700581 msg.body.motion.flags = flags;
582 msg.body.motion.edgeFlags = edgeFlags;
583 msg.body.motion.metaState = metaState;
584 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800585 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700586 msg.body.motion.dsdx = transform.dsdx();
587 msg.body.motion.dtdx = transform.dtdx();
588 msg.body.motion.dtdy = transform.dtdy();
589 msg.body.motion.dsdy = transform.dsdy();
590 msg.body.motion.tx = transform.tx();
591 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700592 msg.body.motion.xPrecision = xPrecision;
593 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700594 msg.body.motion.xCursorPosition = xCursorPosition;
595 msg.body.motion.yCursorPosition = yCursorPosition;
Evan Rosky84f07f02021-04-16 10:42:42 -0700596 msg.body.motion.displayWidth = displayWidth;
597 msg.body.motion.displayHeight = displayHeight;
Jeff Brown5912f952013-07-01 19:10:31 -0700598 msg.body.motion.downTime = downTime;
599 msg.body.motion.eventTime = eventTime;
600 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100601 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700602 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
603 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
604 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700605
Jeff Brown5912f952013-07-01 19:10:31 -0700606 return mChannel->sendMessage(&msg);
607}
608
Garfield Tan1c7bc862020-01-28 13:24:04 -0800609status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
610 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800611 if (ATRACE_ENABLED()) {
612 std::string message =
613 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
614 mChannel->getName().c_str(), toString(hasFocus),
615 toString(inTouchMode));
616 ATRACE_NAME(message.c_str());
617 }
618
619 InputMessage msg;
620 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500621 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800622 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000623 msg.body.focus.hasFocus = hasFocus;
624 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800625 return mChannel->sendMessage(&msg);
626}
627
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800628status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
629 bool pointerCaptureEnabled) {
630 if (ATRACE_ENABLED()) {
631 std::string message =
632 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
633 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
634 ATRACE_NAME(message.c_str());
635 }
636
637 InputMessage msg;
638 msg.header.type = InputMessage::Type::CAPTURE;
639 msg.header.seq = seq;
640 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000641 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800642 return mChannel->sendMessage(&msg);
643}
644
arthurhung7632c332020-12-30 16:58:01 +0800645status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
646 bool isExiting) {
647 if (ATRACE_ENABLED()) {
648 std::string message =
649 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
650 mChannel->getName().c_str(), x, y, toString(isExiting));
651 ATRACE_NAME(message.c_str());
652 }
653
654 InputMessage msg;
655 msg.header.type = InputMessage::Type::DRAG;
656 msg.header.seq = seq;
657 msg.body.drag.eventId = eventId;
658 msg.body.drag.isExiting = isExiting;
659 msg.body.drag.x = x;
660 msg.body.drag.y = y;
661 return mChannel->sendMessage(&msg);
662}
663
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000664android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800665 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000666 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800667 }
Jeff Brown5912f952013-07-01 19:10:31 -0700668
669 InputMessage msg;
670 status_t result = mChannel->receiveMessage(&msg);
671 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000672 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700673 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000674 if (msg.header.type == InputMessage::Type::FINISHED) {
675 return Finished{
676 .seq = msg.header.seq,
677 .handled = msg.body.finished.handled,
678 .consumeTime = msg.body.finished.consumeTime,
679 };
Jeff Brown5912f952013-07-01 19:10:31 -0700680 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000681
682 if (msg.header.type == InputMessage::Type::TIMELINE) {
683 return Timeline{
684 .inputEventId = msg.body.timeline.eventId,
685 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
686 };
687 }
688
689 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
690 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
691 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700692}
693
694// --- InputConsumer ---
695
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500696InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
697 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700698
699InputConsumer::~InputConsumer() {
700}
701
702bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600703 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700704}
705
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800706status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
707 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800708 if (DEBUG_TRANSPORT_ACTIONS) {
709 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
710 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
711 }
Jeff Brown5912f952013-07-01 19:10:31 -0700712
713 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700714 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700715
716 // Fetch the next input message.
717 // Loop until an event can be returned or no additional events are received.
718 while (!*outEvent) {
719 if (mMsgDeferred) {
720 // mMsg contains a valid input message from the previous call to consume
721 // that has not yet been processed.
722 mMsgDeferred = false;
723 } else {
724 // Receive a fresh message.
725 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000726 if (result == OK) {
727 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
728 }
Jeff Brown5912f952013-07-01 19:10:31 -0700729 if (result) {
730 // Consume the next batched event unless batches are being held for later.
731 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800732 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700733 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800734 if (DEBUG_TRANSPORT_ACTIONS) {
735 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
736 mChannel->getName().c_str(), *outSeq);
737 }
Jeff Brown5912f952013-07-01 19:10:31 -0700738 break;
739 }
740 }
741 return result;
742 }
743 }
744
745 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700746 case InputMessage::Type::KEY: {
747 KeyEvent* keyEvent = factory->createKeyEvent();
748 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700749
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700750 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500751 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700752 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800753 if (DEBUG_TRANSPORT_ACTIONS) {
754 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
755 mChannel->getName().c_str(), *outSeq);
756 }
Jeff Brown5912f952013-07-01 19:10:31 -0700757 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700758 }
Jeff Brown5912f952013-07-01 19:10:31 -0700759
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700760 case InputMessage::Type::MOTION: {
761 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
762 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500763 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700764 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500765 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800766 if (DEBUG_TRANSPORT_ACTIONS) {
767 ALOGD("channel '%s' consumer ~ appended to batch event",
768 mChannel->getName().c_str());
769 }
Jeff Brown5912f952013-07-01 19:10:31 -0700770 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700771 } else if (isPointerEvent(mMsg.body.motion.source) &&
772 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
773 // No need to process events that we are going to cancel anyways
774 const size_t count = batch.samples.size();
775 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500776 const InputMessage& msg = batch.samples[i];
777 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700778 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500779 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
780 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700781 } else {
782 // We cannot append to the batch in progress, so we need to consume
783 // the previous batch right now and defer the new message until later.
784 mMsgDeferred = true;
785 status_t result = consumeSamples(factory, batch, batch.samples.size(),
786 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500787 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700788 if (result) {
789 return result;
790 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800791 if (DEBUG_TRANSPORT_ACTIONS) {
792 ALOGD("channel '%s' consumer ~ consumed batch event and "
793 "deferred current event, seq=%u",
794 mChannel->getName().c_str(), *outSeq);
795 }
Jeff Brown5912f952013-07-01 19:10:31 -0700796 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700797 }
Jeff Brown5912f952013-07-01 19:10:31 -0700798 }
Jeff Brown5912f952013-07-01 19:10:31 -0700799
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800800 // Start a new batch if needed.
801 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
802 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500803 Batch batch;
804 batch.samples.push_back(mMsg);
805 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800806 if (DEBUG_TRANSPORT_ACTIONS) {
807 ALOGD("channel '%s' consumer ~ started batch event",
808 mChannel->getName().c_str());
809 }
810 break;
811 }
Jeff Brown5912f952013-07-01 19:10:31 -0700812
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800813 MotionEvent* motionEvent = factory->createMotionEvent();
814 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700815
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800816 updateTouchState(mMsg);
817 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500818 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800819 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800820
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800821 if (DEBUG_TRANSPORT_ACTIONS) {
822 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
823 mChannel->getName().c_str(), *outSeq);
824 }
825 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700826 }
Jeff Brown5912f952013-07-01 19:10:31 -0700827
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000828 case InputMessage::Type::FINISHED:
829 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000830 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
831 "InputConsumer!",
832 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800833 break;
834 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800835
836 case InputMessage::Type::FOCUS: {
837 FocusEvent* focusEvent = factory->createFocusEvent();
838 if (!focusEvent) return NO_MEMORY;
839
840 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500841 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800842 *outEvent = focusEvent;
843 break;
844 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800845
846 case InputMessage::Type::CAPTURE: {
847 CaptureEvent* captureEvent = factory->createCaptureEvent();
848 if (!captureEvent) return NO_MEMORY;
849
850 initializeCaptureEvent(captureEvent, &mMsg);
851 *outSeq = mMsg.header.seq;
852 *outEvent = captureEvent;
853 break;
854 }
arthurhung7632c332020-12-30 16:58:01 +0800855
856 case InputMessage::Type::DRAG: {
857 DragEvent* dragEvent = factory->createDragEvent();
858 if (!dragEvent) return NO_MEMORY;
859
860 initializeDragEvent(dragEvent, &mMsg);
861 *outSeq = mMsg.header.seq;
862 *outEvent = dragEvent;
863 break;
864 }
Jeff Brown5912f952013-07-01 19:10:31 -0700865 }
866 }
867 return OK;
868}
869
870status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800871 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700872 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700873 for (size_t i = mBatches.size(); i > 0; ) {
874 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500875 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700876 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800877 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700879 return result;
880 }
881
Michael Wright32232172013-10-21 12:05:22 -0700882 nsecs_t sampleTime = frameTime;
883 if (mResampleTouch) {
884 sampleTime -= RESAMPLE_LATENCY;
885 }
Jeff Brown5912f952013-07-01 19:10:31 -0700886 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
887 if (split < 0) {
888 continue;
889 }
890
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800891 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700892 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500893 if (batch.samples.empty()) {
894 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700895 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700896 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500897 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700898 }
Michael Wright32232172013-10-21 12:05:22 -0700899 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700900 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
901 }
902 return result;
903 }
904
905 return WOULD_BLOCK;
906}
907
908status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800909 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700910 MotionEvent* motionEvent = factory->createMotionEvent();
911 if (! motionEvent) return NO_MEMORY;
912
913 uint32_t chain = 0;
914 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500915 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100916 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700917 if (i) {
918 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500919 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700920 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500921 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700922 addSample(motionEvent, &msg);
923 } else {
924 initializeMotionEvent(motionEvent, &msg);
925 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500926 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700927 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500928 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700929
930 *outSeq = chain;
931 *outEvent = motionEvent;
932 return OK;
933}
934
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100935void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800936 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700937 return;
938 }
939
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100940 int32_t deviceId = msg.body.motion.deviceId;
941 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700942
943 // Update the touch state history to incorporate the new input message.
944 // If the message is in the past relative to the most recently produced resampled
945 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100946 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700947 case AMOTION_EVENT_ACTION_DOWN: {
948 ssize_t index = findTouchState(deviceId, source);
949 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500950 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700951 index = mTouchStates.size() - 1;
952 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500953 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700954 touchState.initialize(deviceId, source);
955 touchState.addHistory(msg);
956 break;
957 }
958
959 case AMOTION_EVENT_ACTION_MOVE: {
960 ssize_t index = findTouchState(deviceId, source);
961 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500962 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700963 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800964 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700965 }
966 break;
967 }
968
969 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
970 ssize_t index = findTouchState(deviceId, source);
971 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500972 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100973 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700974 rewriteMessage(touchState, msg);
975 }
976 break;
977 }
978
979 case AMOTION_EVENT_ACTION_POINTER_UP: {
980 ssize_t index = findTouchState(deviceId, source);
981 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500982 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700983 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100984 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700985 }
986 break;
987 }
988
989 case AMOTION_EVENT_ACTION_SCROLL: {
990 ssize_t index = findTouchState(deviceId, source);
991 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500992 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700993 rewriteMessage(touchState, msg);
994 }
995 break;
996 }
997
998 case AMOTION_EVENT_ACTION_UP:
999 case AMOTION_EVENT_ACTION_CANCEL: {
1000 ssize_t index = findTouchState(deviceId, source);
1001 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001002 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001003 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001004 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001005 }
1006 break;
1007 }
1008 }
1009}
1010
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001011/**
1012 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1013 *
1014 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1015 * is in the past relative to msg and the past two events do not contain identical coordinates),
1016 * then invalidate the lastResample data for that pointer.
1017 * If the two past events have identical coordinates, then lastResample data for that pointer will
1018 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1019 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1020 * not equal to x0 is received.
1021 */
1022void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001023 nsecs_t eventTime = msg.body.motion.eventTime;
1024 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1025 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001026 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001027 if (eventTime < state.lastResample.eventTime ||
1028 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001029 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1030 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001031#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001032 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1033 resampleCoords.getX(), resampleCoords.getY(),
1034 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001035#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001036 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1037 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1038 } else {
1039 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001040 }
Jeff Brown5912f952013-07-01 19:10:31 -07001041 }
1042 }
1043}
1044
1045void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1046 const InputMessage* next) {
1047 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001048 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001049 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1050 return;
1051 }
1052
1053 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1054 if (index < 0) {
1055#if DEBUG_RESAMPLING
1056 ALOGD("Not resampled, no touch state for device.");
1057#endif
1058 return;
1059 }
1060
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001061 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001062 if (touchState.historySize < 1) {
1063#if DEBUG_RESAMPLING
1064 ALOGD("Not resampled, no history for device.");
1065#endif
1066 return;
1067 }
1068
1069 // Ensure that the current sample has all of the pointers that need to be reported.
1070 const History* current = touchState.getHistory(0);
1071 size_t pointerCount = event->getPointerCount();
1072 for (size_t i = 0; i < pointerCount; i++) {
1073 uint32_t id = event->getPointerId(i);
1074 if (!current->idBits.hasBit(id)) {
1075#if DEBUG_RESAMPLING
1076 ALOGD("Not resampled, missing id %d", id);
1077#endif
1078 return;
1079 }
1080 }
1081
1082 // Find the data to use for resampling.
1083 const History* other;
1084 History future;
1085 float alpha;
1086 if (next) {
1087 // Interpolate between current sample and future sample.
1088 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001089 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001090 other = &future;
1091 nsecs_t delta = future.eventTime - current->eventTime;
1092 if (delta < RESAMPLE_MIN_DELTA) {
1093#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001094 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001095#endif
1096 return;
1097 }
1098 alpha = float(sampleTime - current->eventTime) / delta;
1099 } else if (touchState.historySize >= 2) {
1100 // Extrapolate future sample using current sample and past sample.
1101 // So other->eventTime <= current->eventTime <= sampleTime.
1102 other = touchState.getHistory(1);
1103 nsecs_t delta = current->eventTime - other->eventTime;
1104 if (delta < RESAMPLE_MIN_DELTA) {
1105#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001106 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001107#endif
1108 return;
1109 } else if (delta > RESAMPLE_MAX_DELTA) {
1110#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001111 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001112#endif
1113 return;
1114 }
1115 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1116 if (sampleTime > maxPredict) {
1117#if DEBUG_RESAMPLING
1118 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001119 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001120 sampleTime - current->eventTime, maxPredict - current->eventTime);
1121#endif
1122 sampleTime = maxPredict;
1123 }
1124 alpha = float(current->eventTime - sampleTime) / delta;
1125 } else {
1126#if DEBUG_RESAMPLING
1127 ALOGD("Not resampled, insufficient data.");
1128#endif
1129 return;
1130 }
1131
1132 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001133 History oldLastResample;
1134 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001135 touchState.lastResample.eventTime = sampleTime;
1136 touchState.lastResample.idBits.clear();
1137 for (size_t i = 0; i < pointerCount; i++) {
1138 uint32_t id = event->getPointerId(i);
1139 touchState.lastResample.idToIndex[id] = i;
1140 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001141 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1142 // We maintain the previously resampled value for this pointer (stored in
1143 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1144 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1145
1146 // We know here that the coordinates for the pointer haven't changed because we
1147 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1148 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1149 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1150 continue;
1151 }
1152
Jeff Brown5912f952013-07-01 19:10:31 -07001153 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1154 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001155 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001156 if (other->idBits.hasBit(id)
1157 && shouldResampleTool(event->getToolType(i))) {
1158 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001159 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1160 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1161 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1162 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1163#if DEBUG_RESAMPLING
1164 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1165 "other (%0.3f, %0.3f), alpha %0.3f",
1166 id, resampledCoords.getX(), resampledCoords.getY(),
1167 currentCoords.getX(), currentCoords.getY(),
1168 otherCoords.getX(), otherCoords.getY(),
1169 alpha);
1170#endif
1171 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001172#if DEBUG_RESAMPLING
1173 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1174 id, resampledCoords.getX(), resampledCoords.getY(),
1175 currentCoords.getX(), currentCoords.getY());
1176#endif
1177 }
1178 }
1179
1180 event->addSample(sampleTime, touchState.lastResample.pointers);
1181}
1182
1183bool InputConsumer::shouldResampleTool(int32_t toolType) {
1184 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1185 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1186}
1187
1188status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001189 if (DEBUG_TRANSPORT_ACTIONS) {
1190 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1191 mChannel->getName().c_str(), seq, toString(handled));
1192 }
Jeff Brown5912f952013-07-01 19:10:31 -07001193
1194 if (!seq) {
1195 ALOGE("Attempted to send a finished signal with sequence number 0.");
1196 return BAD_VALUE;
1197 }
1198
1199 // Send finished signals for the batch sequence chain first.
1200 size_t seqChainCount = mSeqChains.size();
1201 if (seqChainCount) {
1202 uint32_t currentSeq = seq;
1203 uint32_t chainSeqs[seqChainCount];
1204 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001205 for (size_t i = seqChainCount; i > 0; ) {
1206 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001207 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001208 if (seqChain.seq == currentSeq) {
1209 currentSeq = seqChain.chain;
1210 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001211 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001212 }
1213 }
1214 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001215 while (!status && chainIndex > 0) {
1216 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001217 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1218 }
1219 if (status) {
1220 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001221 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001222 SeqChain seqChain;
1223 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1224 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001225 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001226 if (!chainIndex) break;
1227 chainIndex--;
1228 }
Jeff Brown5912f952013-07-01 19:10:31 -07001229 return status;
1230 }
1231 }
1232
1233 // Send finished signal for the last message in the batch.
1234 return sendUnchainedFinishedSignal(seq, handled);
1235}
1236
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001237status_t InputConsumer::sendTimeline(int32_t inputEventId,
1238 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1239 if (DEBUG_TRANSPORT_ACTIONS) {
1240 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1241 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1242 mChannel->getName().c_str(), inputEventId,
1243 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1244 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1245 }
1246
1247 InputMessage msg;
1248 msg.header.type = InputMessage::Type::TIMELINE;
1249 msg.header.seq = 0;
1250 msg.body.timeline.eventId = inputEventId;
1251 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1252 return mChannel->sendMessage(&msg);
1253}
1254
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001255nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1256 auto it = mConsumeTimes.find(seq);
1257 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1258 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1259 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1260 seq);
1261 return it->second;
1262}
1263
1264void InputConsumer::popConsumeTime(uint32_t seq) {
1265 mConsumeTimes.erase(seq);
1266}
1267
Jeff Brown5912f952013-07-01 19:10:31 -07001268status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1269 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001270 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001271 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001272 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001273 msg.body.finished.consumeTime = getConsumeTime(seq);
1274 status_t result = mChannel->sendMessage(&msg);
1275 if (result == OK) {
1276 // Remove the consume time if the socket write succeeded. We will not need to ack this
1277 // message anymore. If the socket write did not succeed, we will try again and will still
1278 // need consume time.
1279 popConsumeTime(seq);
1280 }
1281 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001282}
1283
1284bool InputConsumer::hasDeferredEvent() const {
1285 return mMsgDeferred;
1286}
1287
1288bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001289 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001290}
1291
Arthur Hungc7812be2020-02-27 22:40:27 +08001292int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001293 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001294 return AINPUT_SOURCE_CLASS_NONE;
1295 }
1296
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001297 const Batch& batch = mBatches[0];
1298 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001299 return head.body.motion.source;
1300}
1301
Jeff Brown5912f952013-07-01 19:10:31 -07001302ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1303 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001304 const Batch& batch = mBatches[i];
1305 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001306 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1307 return i;
1308 }
1309 }
1310 return -1;
1311}
1312
1313ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1314 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001315 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001316 if (touchState.deviceId == deviceId && touchState.source == source) {
1317 return i;
1318 }
1319 }
1320 return -1;
1321}
1322
1323void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001324 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001325 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1326 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1327 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1328 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001329}
1330
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001331void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001332 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1333 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001334}
1335
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001336void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001337 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001338}
1339
arthurhung7632c332020-12-30 16:58:01 +08001340void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1341 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1342 msg->body.drag.isExiting);
1343}
1344
Jeff Brown5912f952013-07-01 19:10:31 -07001345void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001346 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001347 PointerProperties pointerProperties[pointerCount];
1348 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001349 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001350 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1351 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1352 }
1353
chaviw9eaa22c2020-07-01 16:21:27 -07001354 ui::Transform transform;
1355 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1356 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001357 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1358 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1359 msg->body.motion.actionButton, msg->body.motion.flags,
1360 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001361 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1362 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1363 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07001364 msg->body.motion.displayWidth, msg->body.motion.displayHeight,
chaviw9eaa22c2020-07-01 16:21:27 -07001365 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1366 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001367}
1368
1369void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001370 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001371 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001372 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001373 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1374 }
1375
1376 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1377 event->addSample(msg->body.motion.eventTime, pointerCoords);
1378}
1379
1380bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001381 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001382 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001383 if (head.body.motion.pointerCount != pointerCount
1384 || head.body.motion.action != msg->body.motion.action) {
1385 return false;
1386 }
1387 for (size_t i = 0; i < pointerCount; i++) {
1388 if (head.body.motion.pointers[i].properties
1389 != msg->body.motion.pointers[i].properties) {
1390 return false;
1391 }
1392 }
1393 return true;
1394}
1395
1396ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1397 size_t numSamples = batch.samples.size();
1398 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001399 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001400 index += 1;
1401 }
1402 return ssize_t(index) - 1;
1403}
1404
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001405std::string InputConsumer::dump() const {
1406 std::string out;
1407 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1408 out = out + "mChannel = " + mChannel->getName() + "\n";
1409 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1410 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001411 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001412 }
1413 out += "Batches:\n";
1414 for (const Batch& batch : mBatches) {
1415 out += " Batch:\n";
1416 for (const InputMessage& msg : batch.samples) {
1417 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001418 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001419 switch (msg.header.type) {
1420 case InputMessage::Type::KEY: {
1421 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1422 KeyEvent::actionToString(
1423 msg.body.key.action),
1424 msg.body.key.keyCode);
1425 break;
1426 }
1427 case InputMessage::Type::MOTION: {
1428 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1429 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1430 const float x = msg.body.motion.pointers[i].coords.getX();
1431 const float y = msg.body.motion.pointers[i].coords.getY();
1432 out += android::base::StringPrintf("\n Pointer %" PRIu32
1433 " : x=%.1f y=%.1f",
1434 i, x, y);
1435 }
1436 break;
1437 }
1438 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001439 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1440 toString(msg.body.finished.handled),
1441 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001442 break;
1443 }
1444 case InputMessage::Type::FOCUS: {
1445 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1446 toString(msg.body.focus.hasFocus),
1447 toString(msg.body.focus.inTouchMode));
1448 break;
1449 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001450 case InputMessage::Type::CAPTURE: {
1451 out += android::base::StringPrintf("hasCapture=%s",
1452 toString(msg.body.capture
1453 .pointerCaptureEnabled));
1454 break;
1455 }
arthurhung7632c332020-12-30 16:58:01 +08001456 case InputMessage::Type::DRAG: {
1457 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1458 msg.body.drag.x, msg.body.drag.y,
1459 toString(msg.body.drag.isExiting));
1460 break;
1461 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001462 case InputMessage::Type::TIMELINE: {
1463 const nsecs_t gpuCompletedTime =
1464 msg.body.timeline
1465 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1466 const nsecs_t presentTime =
1467 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1468 out += android::base::StringPrintf("inputEventId=%" PRId32
1469 ", gpuCompletedTime=%" PRId64
1470 ", presentTime=%" PRId64,
1471 msg.body.timeline.eventId, gpuCompletedTime,
1472 presentTime);
1473 break;
1474 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001475 }
1476 out += "\n";
1477 }
1478 }
1479 if (mBatches.empty()) {
1480 out += " <empty>\n";
1481 }
1482 out += "mSeqChains:\n";
1483 for (const SeqChain& chain : mSeqChains) {
1484 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1485 chain.chain);
1486 }
1487 if (mSeqChains.empty()) {
1488 out += " <empty>\n";
1489 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001490 out += "mConsumeTimes:\n";
1491 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1492 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1493 consumeTime);
1494 }
1495 if (mConsumeTimes.empty()) {
1496 out += " <empty>\n";
1497 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001498 return out;
1499}
1500
Jeff Brown5912f952013-07-01 19:10:31 -07001501} // namespace android