blob: f7962e0f099445d03e30a9738d58f70f566ae49a [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
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
Siarhei Vishniakou7766c032021-03-02 20:32:20 +000037#include <input/NamedEnum.h>
Jeff Brown5912f952013-07-01 19:10:31 -070038
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 {
99 if (size() == actualSize) {
100 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700101 case Type::KEY:
102 return true;
103 case Type::MOTION:
104 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
105 case Type::FINISHED:
106 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800107 case Type::FOCUS:
108 return true;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800109 case Type::CAPTURE:
110 return true;
arthurhung7632c332020-12-30 16:58:01 +0800111 case Type::DRAG:
112 return true;
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000113 case Type::TIMELINE:
114 const nsecs_t gpuCompletedTime =
115 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
116 const nsecs_t presentTime =
117 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
118 return presentTime > gpuCompletedTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700119 }
120 }
121 return false;
122}
123
124size_t InputMessage::size() const {
125 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700126 case Type::KEY:
127 return sizeof(Header) + body.key.size();
128 case Type::MOTION:
129 return sizeof(Header) + body.motion.size();
130 case Type::FINISHED:
131 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800132 case Type::FOCUS:
133 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800134 case Type::CAPTURE:
135 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800136 case Type::DRAG:
137 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000138 case Type::TIMELINE:
139 return sizeof(Header) + body.timeline.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700140 }
141 return sizeof(Header);
142}
143
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800144/**
145 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
146 * memory to zero, then only copy the valid bytes on a per-field basis.
147 */
148void InputMessage::getSanitizedCopy(InputMessage* msg) const {
149 memset(msg, 0, sizeof(*msg));
150
151 // Write the header
152 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500153 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800154
155 // Write the body
156 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700157 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800158 // int32_t eventId
159 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800160 // nsecs_t eventTime
161 msg->body.key.eventTime = body.key.eventTime;
162 // int32_t deviceId
163 msg->body.key.deviceId = body.key.deviceId;
164 // int32_t source
165 msg->body.key.source = body.key.source;
166 // int32_t displayId
167 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600168 // std::array<uint8_t, 32> hmac
169 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800170 // int32_t action
171 msg->body.key.action = body.key.action;
172 // int32_t flags
173 msg->body.key.flags = body.key.flags;
174 // int32_t keyCode
175 msg->body.key.keyCode = body.key.keyCode;
176 // int32_t scanCode
177 msg->body.key.scanCode = body.key.scanCode;
178 // int32_t metaState
179 msg->body.key.metaState = body.key.metaState;
180 // int32_t repeatCount
181 msg->body.key.repeatCount = body.key.repeatCount;
182 // nsecs_t downTime
183 msg->body.key.downTime = body.key.downTime;
184 break;
185 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700186 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800187 // int32_t eventId
188 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800189 // nsecs_t eventTime
190 msg->body.motion.eventTime = body.motion.eventTime;
191 // int32_t deviceId
192 msg->body.motion.deviceId = body.motion.deviceId;
193 // int32_t source
194 msg->body.motion.source = body.motion.source;
195 // int32_t displayId
196 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600197 // std::array<uint8_t, 32> hmac
198 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800199 // int32_t action
200 msg->body.motion.action = body.motion.action;
201 // int32_t actionButton
202 msg->body.motion.actionButton = body.motion.actionButton;
203 // int32_t flags
204 msg->body.motion.flags = body.motion.flags;
205 // int32_t metaState
206 msg->body.motion.metaState = body.motion.metaState;
207 // int32_t buttonState
208 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800209 // MotionClassification classification
210 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800211 // int32_t edgeFlags
212 msg->body.motion.edgeFlags = body.motion.edgeFlags;
213 // nsecs_t downTime
214 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700215
216 msg->body.motion.dsdx = body.motion.dsdx;
217 msg->body.motion.dtdx = body.motion.dtdx;
218 msg->body.motion.dtdy = body.motion.dtdy;
219 msg->body.motion.dsdy = body.motion.dsdy;
220 msg->body.motion.tx = body.motion.tx;
221 msg->body.motion.ty = body.motion.ty;
222
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223 // float xPrecision
224 msg->body.motion.xPrecision = body.motion.xPrecision;
225 // float yPrecision
226 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700227 // float xCursorPosition
228 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
229 // float yCursorPosition
230 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800231 // uint32_t pointerCount
232 msg->body.motion.pointerCount = body.motion.pointerCount;
233 //struct Pointer pointers[MAX_POINTERS]
234 for (size_t i = 0; i < body.motion.pointerCount; i++) {
235 // PointerProperties properties
236 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
237 msg->body.motion.pointers[i].properties.toolType =
238 body.motion.pointers[i].properties.toolType,
239 // PointerCoords coords
240 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
241 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
242 memcpy(&msg->body.motion.pointers[i].coords.values[0],
243 &body.motion.pointers[i].coords.values[0],
244 count * (sizeof(body.motion.pointers[i].coords.values[0])));
245 }
246 break;
247 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700248 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800249 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000250 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800251 break;
252 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800253 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800254 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800255 msg->body.focus.hasFocus = body.focus.hasFocus;
256 msg->body.focus.inTouchMode = body.focus.inTouchMode;
257 break;
258 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800259 case InputMessage::Type::CAPTURE: {
260 msg->body.capture.eventId = body.capture.eventId;
261 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
262 break;
263 }
arthurhung7632c332020-12-30 16:58:01 +0800264 case InputMessage::Type::DRAG: {
265 msg->body.drag.eventId = body.drag.eventId;
266 msg->body.drag.x = body.drag.x;
267 msg->body.drag.y = body.drag.y;
268 msg->body.drag.isExiting = body.drag.isExiting;
269 break;
270 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000271 case InputMessage::Type::TIMELINE: {
272 msg->body.timeline.eventId = body.timeline.eventId;
273 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
274 break;
275 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800276 }
277}
Jeff Brown5912f952013-07-01 19:10:31 -0700278
279// --- InputChannel ---
280
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500281std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500282 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700283 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
284 if (result != 0) {
285 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
286 strerror(errno));
287 return nullptr;
288 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500289 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500290 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700291}
292
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500293InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
294 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700295 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500296 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700297 }
Jeff Brown5912f952013-07-01 19:10:31 -0700298}
299
300InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700301 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500302 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700303 }
Robert Carr3720ed02018-08-08 16:08:27 -0700304}
305
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800306status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500307 std::unique_ptr<InputChannel>& outServerChannel,
308 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700309 int sockets[2];
310 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
311 status_t result = -errno;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500312 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d", name.c_str(), errno);
313 outServerChannel.reset();
314 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700315 return result;
316 }
317
318 int bufferSize = SOCKET_BUFFER_SIZE;
319 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
320 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
321 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
322 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
323
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700324 sp<IBinder> token = new BBinder();
325
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700326 std::string serverChannelName = name + " (server)";
327 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700328 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700329
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700330 std::string clientChannelName = name + " (client)";
331 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700332 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700333 return OK;
334}
335
336status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800337 const size_t msgLength = msg->size();
338 InputMessage cleanMsg;
339 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700340 ssize_t nWrite;
341 do {
Chris Ye0783e992020-06-02 21:34:49 -0700342 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700343 } while (nWrite == -1 && errno == EINTR);
344
345 if (nWrite < 0) {
346 int error = errno;
347#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800348 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
349 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700350#endif
351 if (error == EAGAIN || error == EWOULDBLOCK) {
352 return WOULD_BLOCK;
353 }
354 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
355 return DEAD_OBJECT;
356 }
357 return -error;
358 }
359
360 if (size_t(nWrite) != msgLength) {
361#if DEBUG_CHANNEL_MESSAGES
362 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800363 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700364#endif
365 return DEAD_OBJECT;
366 }
367
368#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800369 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700370#endif
371 return OK;
372}
373
374status_t InputChannel::receiveMessage(InputMessage* msg) {
375 ssize_t nRead;
376 do {
Chris Ye0783e992020-06-02 21:34:49 -0700377 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700378 } while (nRead == -1 && errno == EINTR);
379
380 if (nRead < 0) {
381 int error = errno;
382#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800383 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700384#endif
385 if (error == EAGAIN || error == EWOULDBLOCK) {
386 return WOULD_BLOCK;
387 }
388 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
389 return DEAD_OBJECT;
390 }
391 return -error;
392 }
393
394 if (nRead == 0) { // check for EOF
395#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800396 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700397#endif
398 return DEAD_OBJECT;
399 }
400
401 if (!msg->isValid(nRead)) {
402#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800403 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700404#endif
405 return BAD_VALUE;
406 }
407
408#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800409 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700410#endif
411 return OK;
412}
413
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500414std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700415 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700416 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700417}
418
Garfield Tan15601662020-09-22 15:32:38 -0700419void InputChannel::copyTo(InputChannel& outChannel) const {
420 outChannel.mName = getName();
421 outChannel.mFd = dupFd();
422 outChannel.mToken = getConnectionToken();
423}
424
Chris Ye0783e992020-06-02 21:34:49 -0700425status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500426 if (parcel == nullptr) {
427 ALOGE("%s: Null parcel", __func__);
428 return BAD_VALUE;
429 }
430 return parcel->writeStrongBinder(mToken)
431 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700432}
433
Chris Ye0783e992020-06-02 21:34:49 -0700434status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500435 if (parcel == nullptr) {
436 ALOGE("%s: Null parcel", __func__);
437 return BAD_VALUE;
438 }
439 mToken = parcel->readStrongBinder();
440 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700441}
442
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700443sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500444 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700445}
446
Garfield Tan15601662020-09-22 15:32:38 -0700447base::unique_fd InputChannel::dupFd() const {
448 android::base::unique_fd newFd(::dup(getFd()));
449 if (!newFd.ok()) {
450 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
451 strerror(errno));
452 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
453 // If this process is out of file descriptors, then throwing that might end up exploding
454 // on the other side of a binder call, which isn't really helpful.
455 // Better to just crash here and hope that the FD leak is slow.
456 // Other failures could be client errors, so we still propagate those back to the caller.
457 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
458 getName().c_str());
459 return {};
460 }
461 return newFd;
462}
463
Jeff Brown5912f952013-07-01 19:10:31 -0700464// --- InputPublisher ---
465
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500466InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700467
468InputPublisher::~InputPublisher() {
469}
470
Garfield Tan1c7bc862020-01-28 13:24:04 -0800471status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
472 int32_t source, int32_t displayId,
473 std::array<uint8_t, 32> hmac, int32_t action,
474 int32_t flags, int32_t keyCode, int32_t scanCode,
475 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
476 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000477 if (ATRACE_ENABLED()) {
478 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
479 mChannel->getName().c_str(), keyCode);
480 ATRACE_NAME(message.c_str());
481 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800482 if (DEBUG_TRANSPORT_ACTIONS) {
483 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
484 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
485 "downTime=%" PRId64 ", eventTime=%" PRId64,
486 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
487 metaState, repeatCount, downTime, eventTime);
488 }
Jeff Brown5912f952013-07-01 19:10:31 -0700489
490 if (!seq) {
491 ALOGE("Attempted to publish a key event with sequence number 0.");
492 return BAD_VALUE;
493 }
494
495 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700496 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500497 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800498 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700499 msg.body.key.deviceId = deviceId;
500 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100501 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700502 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700503 msg.body.key.action = action;
504 msg.body.key.flags = flags;
505 msg.body.key.keyCode = keyCode;
506 msg.body.key.scanCode = scanCode;
507 msg.body.key.metaState = metaState;
508 msg.body.key.repeatCount = repeatCount;
509 msg.body.key.downTime = downTime;
510 msg.body.key.eventTime = eventTime;
511 return mChannel->sendMessage(&msg);
512}
513
514status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800515 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600516 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
517 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700518 MotionClassification classification, const ui::Transform& transform, float xPrecision,
519 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
520 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
521 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000522 if (ATRACE_ENABLED()) {
523 std::string message = StringPrintf(
524 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
525 mChannel->getName().c_str(), action);
526 ATRACE_NAME(message.c_str());
527 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800528 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700529 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700530 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800531 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
532 "displayId=%" PRId32 ", "
533 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700534 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800535 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700536 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800537 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
538 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700539 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
540 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800541 }
Jeff Brown5912f952013-07-01 19:10:31 -0700542
543 if (!seq) {
544 ALOGE("Attempted to publish a motion event with sequence number 0.");
545 return BAD_VALUE;
546 }
547
548 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700549 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800550 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700551 return BAD_VALUE;
552 }
553
554 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700555 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500556 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800557 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700558 msg.body.motion.deviceId = deviceId;
559 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700560 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700561 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700562 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100563 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700564 msg.body.motion.flags = flags;
565 msg.body.motion.edgeFlags = edgeFlags;
566 msg.body.motion.metaState = metaState;
567 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800568 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700569 msg.body.motion.dsdx = transform.dsdx();
570 msg.body.motion.dtdx = transform.dtdx();
571 msg.body.motion.dtdy = transform.dtdy();
572 msg.body.motion.dsdy = transform.dsdy();
573 msg.body.motion.tx = transform.tx();
574 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700575 msg.body.motion.xPrecision = xPrecision;
576 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700577 msg.body.motion.xCursorPosition = xCursorPosition;
578 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700579 msg.body.motion.downTime = downTime;
580 msg.body.motion.eventTime = eventTime;
581 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100582 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700583 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
584 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
585 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700586
Jeff Brown5912f952013-07-01 19:10:31 -0700587 return mChannel->sendMessage(&msg);
588}
589
Garfield Tan1c7bc862020-01-28 13:24:04 -0800590status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
591 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800592 if (ATRACE_ENABLED()) {
593 std::string message =
594 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
595 mChannel->getName().c_str(), toString(hasFocus),
596 toString(inTouchMode));
597 ATRACE_NAME(message.c_str());
598 }
599
600 InputMessage msg;
601 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500602 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800603 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000604 msg.body.focus.hasFocus = hasFocus;
605 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800606 return mChannel->sendMessage(&msg);
607}
608
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800609status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
610 bool pointerCaptureEnabled) {
611 if (ATRACE_ENABLED()) {
612 std::string message =
613 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
614 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
615 ATRACE_NAME(message.c_str());
616 }
617
618 InputMessage msg;
619 msg.header.type = InputMessage::Type::CAPTURE;
620 msg.header.seq = seq;
621 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000622 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800623 return mChannel->sendMessage(&msg);
624}
625
arthurhung7632c332020-12-30 16:58:01 +0800626status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
627 bool isExiting) {
628 if (ATRACE_ENABLED()) {
629 std::string message =
630 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
631 mChannel->getName().c_str(), x, y, toString(isExiting));
632 ATRACE_NAME(message.c_str());
633 }
634
635 InputMessage msg;
636 msg.header.type = InputMessage::Type::DRAG;
637 msg.header.seq = seq;
638 msg.body.drag.eventId = eventId;
639 msg.body.drag.isExiting = isExiting;
640 msg.body.drag.x = x;
641 msg.body.drag.y = y;
642 return mChannel->sendMessage(&msg);
643}
644
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000645android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800646 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000647 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800648 }
Jeff Brown5912f952013-07-01 19:10:31 -0700649
650 InputMessage msg;
651 status_t result = mChannel->receiveMessage(&msg);
652 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000653 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700654 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000655 if (msg.header.type == InputMessage::Type::FINISHED) {
656 return Finished{
657 .seq = msg.header.seq,
658 .handled = msg.body.finished.handled,
659 .consumeTime = msg.body.finished.consumeTime,
660 };
Jeff Brown5912f952013-07-01 19:10:31 -0700661 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000662
663 if (msg.header.type == InputMessage::Type::TIMELINE) {
664 return Timeline{
665 .inputEventId = msg.body.timeline.eventId,
666 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
667 };
668 }
669
670 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
671 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
672 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700673}
674
675// --- InputConsumer ---
676
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500677InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
678 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700679
680InputConsumer::~InputConsumer() {
681}
682
683bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600684 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700685}
686
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800687status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
688 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800689 if (DEBUG_TRANSPORT_ACTIONS) {
690 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
691 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
692 }
Jeff Brown5912f952013-07-01 19:10:31 -0700693
694 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700695 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700696
697 // Fetch the next input message.
698 // Loop until an event can be returned or no additional events are received.
699 while (!*outEvent) {
700 if (mMsgDeferred) {
701 // mMsg contains a valid input message from the previous call to consume
702 // that has not yet been processed.
703 mMsgDeferred = false;
704 } else {
705 // Receive a fresh message.
706 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000707 if (result == OK) {
708 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
709 }
Jeff Brown5912f952013-07-01 19:10:31 -0700710 if (result) {
711 // Consume the next batched event unless batches are being held for later.
712 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800713 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700714 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800715 if (DEBUG_TRANSPORT_ACTIONS) {
716 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
717 mChannel->getName().c_str(), *outSeq);
718 }
Jeff Brown5912f952013-07-01 19:10:31 -0700719 break;
720 }
721 }
722 return result;
723 }
724 }
725
726 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700727 case InputMessage::Type::KEY: {
728 KeyEvent* keyEvent = factory->createKeyEvent();
729 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700730
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700731 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500732 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700733 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800734 if (DEBUG_TRANSPORT_ACTIONS) {
735 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
736 mChannel->getName().c_str(), *outSeq);
737 }
Jeff Brown5912f952013-07-01 19:10:31 -0700738 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700739 }
Jeff Brown5912f952013-07-01 19:10:31 -0700740
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700741 case InputMessage::Type::MOTION: {
742 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
743 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500744 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700745 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500746 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800747 if (DEBUG_TRANSPORT_ACTIONS) {
748 ALOGD("channel '%s' consumer ~ appended to batch event",
749 mChannel->getName().c_str());
750 }
Jeff Brown5912f952013-07-01 19:10:31 -0700751 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700752 } else if (isPointerEvent(mMsg.body.motion.source) &&
753 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
754 // No need to process events that we are going to cancel anyways
755 const size_t count = batch.samples.size();
756 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500757 const InputMessage& msg = batch.samples[i];
758 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700759 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500760 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
761 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700762 } else {
763 // We cannot append to the batch in progress, so we need to consume
764 // the previous batch right now and defer the new message until later.
765 mMsgDeferred = true;
766 status_t result = consumeSamples(factory, batch, batch.samples.size(),
767 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500768 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700769 if (result) {
770 return result;
771 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800772 if (DEBUG_TRANSPORT_ACTIONS) {
773 ALOGD("channel '%s' consumer ~ consumed batch event and "
774 "deferred current event, seq=%u",
775 mChannel->getName().c_str(), *outSeq);
776 }
Jeff Brown5912f952013-07-01 19:10:31 -0700777 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700778 }
Jeff Brown5912f952013-07-01 19:10:31 -0700779 }
Jeff Brown5912f952013-07-01 19:10:31 -0700780
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800781 // Start a new batch if needed.
782 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
783 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500784 Batch batch;
785 batch.samples.push_back(mMsg);
786 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800787 if (DEBUG_TRANSPORT_ACTIONS) {
788 ALOGD("channel '%s' consumer ~ started batch event",
789 mChannel->getName().c_str());
790 }
791 break;
792 }
Jeff Brown5912f952013-07-01 19:10:31 -0700793
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800794 MotionEvent* motionEvent = factory->createMotionEvent();
795 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700796
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800797 updateTouchState(mMsg);
798 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500799 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800800 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800801
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800802 if (DEBUG_TRANSPORT_ACTIONS) {
803 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
804 mChannel->getName().c_str(), *outSeq);
805 }
806 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700807 }
Jeff Brown5912f952013-07-01 19:10:31 -0700808
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809 case InputMessage::Type::FINISHED:
810 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000811 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
812 "InputConsumer!",
813 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800814 break;
815 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800816
817 case InputMessage::Type::FOCUS: {
818 FocusEvent* focusEvent = factory->createFocusEvent();
819 if (!focusEvent) return NO_MEMORY;
820
821 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500822 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800823 *outEvent = focusEvent;
824 break;
825 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800826
827 case InputMessage::Type::CAPTURE: {
828 CaptureEvent* captureEvent = factory->createCaptureEvent();
829 if (!captureEvent) return NO_MEMORY;
830
831 initializeCaptureEvent(captureEvent, &mMsg);
832 *outSeq = mMsg.header.seq;
833 *outEvent = captureEvent;
834 break;
835 }
arthurhung7632c332020-12-30 16:58:01 +0800836
837 case InputMessage::Type::DRAG: {
838 DragEvent* dragEvent = factory->createDragEvent();
839 if (!dragEvent) return NO_MEMORY;
840
841 initializeDragEvent(dragEvent, &mMsg);
842 *outSeq = mMsg.header.seq;
843 *outEvent = dragEvent;
844 break;
845 }
Jeff Brown5912f952013-07-01 19:10:31 -0700846 }
847 }
848 return OK;
849}
850
851status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800852 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700853 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700854 for (size_t i = mBatches.size(); i > 0; ) {
855 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500856 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700857 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800858 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500859 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700860 return result;
861 }
862
Michael Wright32232172013-10-21 12:05:22 -0700863 nsecs_t sampleTime = frameTime;
864 if (mResampleTouch) {
865 sampleTime -= RESAMPLE_LATENCY;
866 }
Jeff Brown5912f952013-07-01 19:10:31 -0700867 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
868 if (split < 0) {
869 continue;
870 }
871
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800872 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700873 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500874 if (batch.samples.empty()) {
875 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700876 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700877 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700879 }
Michael Wright32232172013-10-21 12:05:22 -0700880 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700881 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
882 }
883 return result;
884 }
885
886 return WOULD_BLOCK;
887}
888
889status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800890 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700891 MotionEvent* motionEvent = factory->createMotionEvent();
892 if (! motionEvent) return NO_MEMORY;
893
894 uint32_t chain = 0;
895 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500896 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100897 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700898 if (i) {
899 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500900 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700901 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500902 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700903 addSample(motionEvent, &msg);
904 } else {
905 initializeMotionEvent(motionEvent, &msg);
906 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500907 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700908 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500909 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700910
911 *outSeq = chain;
912 *outEvent = motionEvent;
913 return OK;
914}
915
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100916void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800917 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700918 return;
919 }
920
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100921 int32_t deviceId = msg.body.motion.deviceId;
922 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700923
924 // Update the touch state history to incorporate the new input message.
925 // If the message is in the past relative to the most recently produced resampled
926 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100927 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700928 case AMOTION_EVENT_ACTION_DOWN: {
929 ssize_t index = findTouchState(deviceId, source);
930 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500931 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700932 index = mTouchStates.size() - 1;
933 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500934 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700935 touchState.initialize(deviceId, source);
936 touchState.addHistory(msg);
937 break;
938 }
939
940 case AMOTION_EVENT_ACTION_MOVE: {
941 ssize_t index = findTouchState(deviceId, source);
942 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500943 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700944 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800945 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700946 }
947 break;
948 }
949
950 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
951 ssize_t index = findTouchState(deviceId, source);
952 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500953 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100954 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700955 rewriteMessage(touchState, msg);
956 }
957 break;
958 }
959
960 case AMOTION_EVENT_ACTION_POINTER_UP: {
961 ssize_t index = findTouchState(deviceId, source);
962 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500963 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700964 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100965 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700966 }
967 break;
968 }
969
970 case AMOTION_EVENT_ACTION_SCROLL: {
971 ssize_t index = findTouchState(deviceId, source);
972 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500973 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700974 rewriteMessage(touchState, msg);
975 }
976 break;
977 }
978
979 case AMOTION_EVENT_ACTION_UP:
980 case AMOTION_EVENT_ACTION_CANCEL: {
981 ssize_t index = findTouchState(deviceId, source);
982 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500983 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700984 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500985 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700986 }
987 break;
988 }
989 }
990}
991
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800992/**
993 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
994 *
995 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
996 * is in the past relative to msg and the past two events do not contain identical coordinates),
997 * then invalidate the lastResample data for that pointer.
998 * If the two past events have identical coordinates, then lastResample data for that pointer will
999 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1000 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1001 * not equal to x0 is received.
1002 */
1003void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001004 nsecs_t eventTime = msg.body.motion.eventTime;
1005 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1006 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001007 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001008 if (eventTime < state.lastResample.eventTime ||
1009 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001010 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1011 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001012#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001013 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1014 resampleCoords.getX(), resampleCoords.getY(),
1015 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001016#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001017 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1018 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1019 } else {
1020 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001021 }
Jeff Brown5912f952013-07-01 19:10:31 -07001022 }
1023 }
1024}
1025
1026void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1027 const InputMessage* next) {
1028 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001029 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001030 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1031 return;
1032 }
1033
1034 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1035 if (index < 0) {
1036#if DEBUG_RESAMPLING
1037 ALOGD("Not resampled, no touch state for device.");
1038#endif
1039 return;
1040 }
1041
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001042 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001043 if (touchState.historySize < 1) {
1044#if DEBUG_RESAMPLING
1045 ALOGD("Not resampled, no history for device.");
1046#endif
1047 return;
1048 }
1049
1050 // Ensure that the current sample has all of the pointers that need to be reported.
1051 const History* current = touchState.getHistory(0);
1052 size_t pointerCount = event->getPointerCount();
1053 for (size_t i = 0; i < pointerCount; i++) {
1054 uint32_t id = event->getPointerId(i);
1055 if (!current->idBits.hasBit(id)) {
1056#if DEBUG_RESAMPLING
1057 ALOGD("Not resampled, missing id %d", id);
1058#endif
1059 return;
1060 }
1061 }
1062
1063 // Find the data to use for resampling.
1064 const History* other;
1065 History future;
1066 float alpha;
1067 if (next) {
1068 // Interpolate between current sample and future sample.
1069 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001070 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001071 other = &future;
1072 nsecs_t delta = future.eventTime - current->eventTime;
1073 if (delta < RESAMPLE_MIN_DELTA) {
1074#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001075 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001076#endif
1077 return;
1078 }
1079 alpha = float(sampleTime - current->eventTime) / delta;
1080 } else if (touchState.historySize >= 2) {
1081 // Extrapolate future sample using current sample and past sample.
1082 // So other->eventTime <= current->eventTime <= sampleTime.
1083 other = touchState.getHistory(1);
1084 nsecs_t delta = current->eventTime - other->eventTime;
1085 if (delta < RESAMPLE_MIN_DELTA) {
1086#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001087 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001088#endif
1089 return;
1090 } else if (delta > RESAMPLE_MAX_DELTA) {
1091#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001092 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001093#endif
1094 return;
1095 }
1096 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1097 if (sampleTime > maxPredict) {
1098#if DEBUG_RESAMPLING
1099 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001100 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001101 sampleTime - current->eventTime, maxPredict - current->eventTime);
1102#endif
1103 sampleTime = maxPredict;
1104 }
1105 alpha = float(current->eventTime - sampleTime) / delta;
1106 } else {
1107#if DEBUG_RESAMPLING
1108 ALOGD("Not resampled, insufficient data.");
1109#endif
1110 return;
1111 }
1112
1113 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001114 History oldLastResample;
1115 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001116 touchState.lastResample.eventTime = sampleTime;
1117 touchState.lastResample.idBits.clear();
1118 for (size_t i = 0; i < pointerCount; i++) {
1119 uint32_t id = event->getPointerId(i);
1120 touchState.lastResample.idToIndex[id] = i;
1121 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001122 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1123 // We maintain the previously resampled value for this pointer (stored in
1124 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1125 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1126
1127 // We know here that the coordinates for the pointer haven't changed because we
1128 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1129 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1130 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1131 continue;
1132 }
1133
Jeff Brown5912f952013-07-01 19:10:31 -07001134 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1135 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001136 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001137 if (other->idBits.hasBit(id)
1138 && shouldResampleTool(event->getToolType(i))) {
1139 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001140 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1141 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1142 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1143 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1144#if DEBUG_RESAMPLING
1145 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1146 "other (%0.3f, %0.3f), alpha %0.3f",
1147 id, resampledCoords.getX(), resampledCoords.getY(),
1148 currentCoords.getX(), currentCoords.getY(),
1149 otherCoords.getX(), otherCoords.getY(),
1150 alpha);
1151#endif
1152 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001153#if DEBUG_RESAMPLING
1154 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1155 id, resampledCoords.getX(), resampledCoords.getY(),
1156 currentCoords.getX(), currentCoords.getY());
1157#endif
1158 }
1159 }
1160
1161 event->addSample(sampleTime, touchState.lastResample.pointers);
1162}
1163
1164bool InputConsumer::shouldResampleTool(int32_t toolType) {
1165 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1166 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1167}
1168
1169status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001170 if (DEBUG_TRANSPORT_ACTIONS) {
1171 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1172 mChannel->getName().c_str(), seq, toString(handled));
1173 }
Jeff Brown5912f952013-07-01 19:10:31 -07001174
1175 if (!seq) {
1176 ALOGE("Attempted to send a finished signal with sequence number 0.");
1177 return BAD_VALUE;
1178 }
1179
1180 // Send finished signals for the batch sequence chain first.
1181 size_t seqChainCount = mSeqChains.size();
1182 if (seqChainCount) {
1183 uint32_t currentSeq = seq;
1184 uint32_t chainSeqs[seqChainCount];
1185 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001186 for (size_t i = seqChainCount; i > 0; ) {
1187 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001188 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001189 if (seqChain.seq == currentSeq) {
1190 currentSeq = seqChain.chain;
1191 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001192 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001193 }
1194 }
1195 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001196 while (!status && chainIndex > 0) {
1197 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001198 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1199 }
1200 if (status) {
1201 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001202 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001203 SeqChain seqChain;
1204 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1205 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001206 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001207 if (!chainIndex) break;
1208 chainIndex--;
1209 }
Jeff Brown5912f952013-07-01 19:10:31 -07001210 return status;
1211 }
1212 }
1213
1214 // Send finished signal for the last message in the batch.
1215 return sendUnchainedFinishedSignal(seq, handled);
1216}
1217
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001218status_t InputConsumer::sendTimeline(int32_t inputEventId,
1219 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1220 if (DEBUG_TRANSPORT_ACTIONS) {
1221 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1222 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1223 mChannel->getName().c_str(), inputEventId,
1224 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1225 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1226 }
1227
1228 InputMessage msg;
1229 msg.header.type = InputMessage::Type::TIMELINE;
1230 msg.header.seq = 0;
1231 msg.body.timeline.eventId = inputEventId;
1232 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1233 return mChannel->sendMessage(&msg);
1234}
1235
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001236nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1237 auto it = mConsumeTimes.find(seq);
1238 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1239 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1240 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1241 seq);
1242 return it->second;
1243}
1244
1245void InputConsumer::popConsumeTime(uint32_t seq) {
1246 mConsumeTimes.erase(seq);
1247}
1248
Jeff Brown5912f952013-07-01 19:10:31 -07001249status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1250 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001251 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001252 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001253 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001254 msg.body.finished.consumeTime = getConsumeTime(seq);
1255 status_t result = mChannel->sendMessage(&msg);
1256 if (result == OK) {
1257 // Remove the consume time if the socket write succeeded. We will not need to ack this
1258 // message anymore. If the socket write did not succeed, we will try again and will still
1259 // need consume time.
1260 popConsumeTime(seq);
1261 }
1262 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001263}
1264
1265bool InputConsumer::hasDeferredEvent() const {
1266 return mMsgDeferred;
1267}
1268
1269bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001270 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001271}
1272
Arthur Hungc7812be2020-02-27 22:40:27 +08001273int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001274 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001275 return AINPUT_SOURCE_CLASS_NONE;
1276 }
1277
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001278 const Batch& batch = mBatches[0];
1279 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001280 return head.body.motion.source;
1281}
1282
Jeff Brown5912f952013-07-01 19:10:31 -07001283ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1284 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001285 const Batch& batch = mBatches[i];
1286 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001287 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1288 return i;
1289 }
1290 }
1291 return -1;
1292}
1293
1294ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1295 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001296 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001297 if (touchState.deviceId == deviceId && touchState.source == source) {
1298 return i;
1299 }
1300 }
1301 return -1;
1302}
1303
1304void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001305 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001306 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1307 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1308 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1309 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001310}
1311
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001312void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001313 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1314 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001315}
1316
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001317void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001318 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001319}
1320
arthurhung7632c332020-12-30 16:58:01 +08001321void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1322 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1323 msg->body.drag.isExiting);
1324}
1325
Jeff Brown5912f952013-07-01 19:10:31 -07001326void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001327 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001328 PointerProperties pointerProperties[pointerCount];
1329 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001330 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001331 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1332 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1333 }
1334
chaviw9eaa22c2020-07-01 16:21:27 -07001335 ui::Transform transform;
1336 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1337 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001338 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1339 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1340 msg->body.motion.actionButton, msg->body.motion.flags,
1341 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001342 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1343 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1344 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1345 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1346 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001347}
1348
1349void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001350 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001351 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001352 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001353 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1354 }
1355
1356 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1357 event->addSample(msg->body.motion.eventTime, pointerCoords);
1358}
1359
1360bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001361 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001362 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001363 if (head.body.motion.pointerCount != pointerCount
1364 || head.body.motion.action != msg->body.motion.action) {
1365 return false;
1366 }
1367 for (size_t i = 0; i < pointerCount; i++) {
1368 if (head.body.motion.pointers[i].properties
1369 != msg->body.motion.pointers[i].properties) {
1370 return false;
1371 }
1372 }
1373 return true;
1374}
1375
1376ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1377 size_t numSamples = batch.samples.size();
1378 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001379 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001380 index += 1;
1381 }
1382 return ssize_t(index) - 1;
1383}
1384
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001385std::string InputConsumer::dump() const {
1386 std::string out;
1387 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1388 out = out + "mChannel = " + mChannel->getName() + "\n";
1389 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1390 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001391 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001392 }
1393 out += "Batches:\n";
1394 for (const Batch& batch : mBatches) {
1395 out += " Batch:\n";
1396 for (const InputMessage& msg : batch.samples) {
1397 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001398 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001399 switch (msg.header.type) {
1400 case InputMessage::Type::KEY: {
1401 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1402 KeyEvent::actionToString(
1403 msg.body.key.action),
1404 msg.body.key.keyCode);
1405 break;
1406 }
1407 case InputMessage::Type::MOTION: {
1408 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1409 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1410 const float x = msg.body.motion.pointers[i].coords.getX();
1411 const float y = msg.body.motion.pointers[i].coords.getY();
1412 out += android::base::StringPrintf("\n Pointer %" PRIu32
1413 " : x=%.1f y=%.1f",
1414 i, x, y);
1415 }
1416 break;
1417 }
1418 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001419 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1420 toString(msg.body.finished.handled),
1421 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001422 break;
1423 }
1424 case InputMessage::Type::FOCUS: {
1425 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1426 toString(msg.body.focus.hasFocus),
1427 toString(msg.body.focus.inTouchMode));
1428 break;
1429 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001430 case InputMessage::Type::CAPTURE: {
1431 out += android::base::StringPrintf("hasCapture=%s",
1432 toString(msg.body.capture
1433 .pointerCaptureEnabled));
1434 break;
1435 }
arthurhung7632c332020-12-30 16:58:01 +08001436 case InputMessage::Type::DRAG: {
1437 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1438 msg.body.drag.x, msg.body.drag.y,
1439 toString(msg.body.drag.isExiting));
1440 break;
1441 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001442 case InputMessage::Type::TIMELINE: {
1443 const nsecs_t gpuCompletedTime =
1444 msg.body.timeline
1445 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1446 const nsecs_t presentTime =
1447 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1448 out += android::base::StringPrintf("inputEventId=%" PRId32
1449 ", gpuCompletedTime=%" PRId64
1450 ", presentTime=%" PRId64,
1451 msg.body.timeline.eventId, gpuCompletedTime,
1452 presentTime);
1453 break;
1454 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001455 }
1456 out += "\n";
1457 }
1458 }
1459 if (mBatches.empty()) {
1460 out += " <empty>\n";
1461 }
1462 out += "mSeqChains:\n";
1463 for (const SeqChain& chain : mSeqChains) {
1464 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1465 chain.chain);
1466 }
1467 if (mSeqChains.empty()) {
1468 out += " <empty>\n";
1469 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001470 out += "mConsumeTimes:\n";
1471 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1472 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1473 consumeTime);
1474 }
1475 if (mConsumeTimes.empty()) {
1476 out += " <empty>\n";
1477 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001478 return out;
1479}
1480
Jeff Brown5912f952013-07-01 19:10:31 -07001481} // namespace android