blob: 56a064bd26ec88bd2ed280835afdcd9696b53c8e [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 Vishniakou09b02ac2021-04-14 22:24:04 +0000312 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
313 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500314 outServerChannel.reset();
315 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700316 return result;
317 }
318
319 int bufferSize = SOCKET_BUFFER_SIZE;
320 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
321 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
322 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
323 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
324
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700325 sp<IBinder> token = new BBinder();
326
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700327 std::string serverChannelName = name + " (server)";
328 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700329 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700330
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700331 std::string clientChannelName = name + " (client)";
332 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700333 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700334 return OK;
335}
336
337status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800338 const size_t msgLength = msg->size();
339 InputMessage cleanMsg;
340 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700341 ssize_t nWrite;
342 do {
Chris Ye0783e992020-06-02 21:34:49 -0700343 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700344 } while (nWrite == -1 && errno == EINTR);
345
346 if (nWrite < 0) {
347 int error = errno;
348#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800349 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
350 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700351#endif
352 if (error == EAGAIN || error == EWOULDBLOCK) {
353 return WOULD_BLOCK;
354 }
355 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
356 return DEAD_OBJECT;
357 }
358 return -error;
359 }
360
361 if (size_t(nWrite) != msgLength) {
362#if DEBUG_CHANNEL_MESSAGES
363 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800364 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700365#endif
366 return DEAD_OBJECT;
367 }
368
369#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800370 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700371#endif
372 return OK;
373}
374
375status_t InputChannel::receiveMessage(InputMessage* msg) {
376 ssize_t nRead;
377 do {
Chris Ye0783e992020-06-02 21:34:49 -0700378 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700379 } while (nRead == -1 && errno == EINTR);
380
381 if (nRead < 0) {
382 int error = errno;
383#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800384 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700385#endif
386 if (error == EAGAIN || error == EWOULDBLOCK) {
387 return WOULD_BLOCK;
388 }
389 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
390 return DEAD_OBJECT;
391 }
392 return -error;
393 }
394
395 if (nRead == 0) { // check for EOF
396#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800397 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700398#endif
399 return DEAD_OBJECT;
400 }
401
402 if (!msg->isValid(nRead)) {
403#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800404 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700405#endif
406 return BAD_VALUE;
407 }
408
409#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800410 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700411#endif
412 return OK;
413}
414
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500415std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700416 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700417 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700418}
419
Garfield Tan15601662020-09-22 15:32:38 -0700420void InputChannel::copyTo(InputChannel& outChannel) const {
421 outChannel.mName = getName();
422 outChannel.mFd = dupFd();
423 outChannel.mToken = getConnectionToken();
424}
425
Chris Ye0783e992020-06-02 21:34:49 -0700426status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500427 if (parcel == nullptr) {
428 ALOGE("%s: Null parcel", __func__);
429 return BAD_VALUE;
430 }
431 return parcel->writeStrongBinder(mToken)
432 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700433}
434
Chris Ye0783e992020-06-02 21:34:49 -0700435status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500436 if (parcel == nullptr) {
437 ALOGE("%s: Null parcel", __func__);
438 return BAD_VALUE;
439 }
440 mToken = parcel->readStrongBinder();
441 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700442}
443
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700444sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500445 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700446}
447
Garfield Tan15601662020-09-22 15:32:38 -0700448base::unique_fd InputChannel::dupFd() const {
449 android::base::unique_fd newFd(::dup(getFd()));
450 if (!newFd.ok()) {
451 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
452 strerror(errno));
453 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
454 // If this process is out of file descriptors, then throwing that might end up exploding
455 // on the other side of a binder call, which isn't really helpful.
456 // Better to just crash here and hope that the FD leak is slow.
457 // Other failures could be client errors, so we still propagate those back to the caller.
458 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
459 getName().c_str());
460 return {};
461 }
462 return newFd;
463}
464
Jeff Brown5912f952013-07-01 19:10:31 -0700465// --- InputPublisher ---
466
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500467InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700468
469InputPublisher::~InputPublisher() {
470}
471
Garfield Tan1c7bc862020-01-28 13:24:04 -0800472status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
473 int32_t source, int32_t displayId,
474 std::array<uint8_t, 32> hmac, int32_t action,
475 int32_t flags, int32_t keyCode, int32_t scanCode,
476 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
477 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000478 if (ATRACE_ENABLED()) {
479 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
480 mChannel->getName().c_str(), keyCode);
481 ATRACE_NAME(message.c_str());
482 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800483 if (DEBUG_TRANSPORT_ACTIONS) {
484 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
485 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
486 "downTime=%" PRId64 ", eventTime=%" PRId64,
487 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
488 metaState, repeatCount, downTime, eventTime);
489 }
Jeff Brown5912f952013-07-01 19:10:31 -0700490
491 if (!seq) {
492 ALOGE("Attempted to publish a key event with sequence number 0.");
493 return BAD_VALUE;
494 }
495
496 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700497 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500498 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800499 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700500 msg.body.key.deviceId = deviceId;
501 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100502 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700503 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700504 msg.body.key.action = action;
505 msg.body.key.flags = flags;
506 msg.body.key.keyCode = keyCode;
507 msg.body.key.scanCode = scanCode;
508 msg.body.key.metaState = metaState;
509 msg.body.key.repeatCount = repeatCount;
510 msg.body.key.downTime = downTime;
511 msg.body.key.eventTime = eventTime;
512 return mChannel->sendMessage(&msg);
513}
514
515status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800516 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600517 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
518 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700519 MotionClassification classification, const ui::Transform& transform, float xPrecision,
520 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
521 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
522 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000523 if (ATRACE_ENABLED()) {
524 std::string message = StringPrintf(
525 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
526 mChannel->getName().c_str(), action);
527 ATRACE_NAME(message.c_str());
528 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800529 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700530 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700531 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800532 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
533 "displayId=%" PRId32 ", "
534 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700535 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800536 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700537 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800538 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
539 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700540 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
541 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800542 }
Jeff Brown5912f952013-07-01 19:10:31 -0700543
544 if (!seq) {
545 ALOGE("Attempted to publish a motion event with sequence number 0.");
546 return BAD_VALUE;
547 }
548
549 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700550 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800551 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700552 return BAD_VALUE;
553 }
554
555 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700556 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500557 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800558 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700559 msg.body.motion.deviceId = deviceId;
560 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700561 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700562 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700563 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100564 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700565 msg.body.motion.flags = flags;
566 msg.body.motion.edgeFlags = edgeFlags;
567 msg.body.motion.metaState = metaState;
568 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800569 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700570 msg.body.motion.dsdx = transform.dsdx();
571 msg.body.motion.dtdx = transform.dtdx();
572 msg.body.motion.dtdy = transform.dtdy();
573 msg.body.motion.dsdy = transform.dsdy();
574 msg.body.motion.tx = transform.tx();
575 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700576 msg.body.motion.xPrecision = xPrecision;
577 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700578 msg.body.motion.xCursorPosition = xCursorPosition;
579 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700580 msg.body.motion.downTime = downTime;
581 msg.body.motion.eventTime = eventTime;
582 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100583 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700584 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
585 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
586 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700587
Jeff Brown5912f952013-07-01 19:10:31 -0700588 return mChannel->sendMessage(&msg);
589}
590
Garfield Tan1c7bc862020-01-28 13:24:04 -0800591status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
592 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800593 if (ATRACE_ENABLED()) {
594 std::string message =
595 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
596 mChannel->getName().c_str(), toString(hasFocus),
597 toString(inTouchMode));
598 ATRACE_NAME(message.c_str());
599 }
600
601 InputMessage msg;
602 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500603 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800604 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000605 msg.body.focus.hasFocus = hasFocus;
606 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800607 return mChannel->sendMessage(&msg);
608}
609
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800610status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
611 bool pointerCaptureEnabled) {
612 if (ATRACE_ENABLED()) {
613 std::string message =
614 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
615 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
616 ATRACE_NAME(message.c_str());
617 }
618
619 InputMessage msg;
620 msg.header.type = InputMessage::Type::CAPTURE;
621 msg.header.seq = seq;
622 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000623 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800624 return mChannel->sendMessage(&msg);
625}
626
arthurhung7632c332020-12-30 16:58:01 +0800627status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
628 bool isExiting) {
629 if (ATRACE_ENABLED()) {
630 std::string message =
631 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
632 mChannel->getName().c_str(), x, y, toString(isExiting));
633 ATRACE_NAME(message.c_str());
634 }
635
636 InputMessage msg;
637 msg.header.type = InputMessage::Type::DRAG;
638 msg.header.seq = seq;
639 msg.body.drag.eventId = eventId;
640 msg.body.drag.isExiting = isExiting;
641 msg.body.drag.x = x;
642 msg.body.drag.y = y;
643 return mChannel->sendMessage(&msg);
644}
645
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000646android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800647 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000648 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800649 }
Jeff Brown5912f952013-07-01 19:10:31 -0700650
651 InputMessage msg;
652 status_t result = mChannel->receiveMessage(&msg);
653 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000654 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700655 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000656 if (msg.header.type == InputMessage::Type::FINISHED) {
657 return Finished{
658 .seq = msg.header.seq,
659 .handled = msg.body.finished.handled,
660 .consumeTime = msg.body.finished.consumeTime,
661 };
Jeff Brown5912f952013-07-01 19:10:31 -0700662 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000663
664 if (msg.header.type == InputMessage::Type::TIMELINE) {
665 return Timeline{
666 .inputEventId = msg.body.timeline.eventId,
667 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
668 };
669 }
670
671 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
672 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
673 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700674}
675
676// --- InputConsumer ---
677
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500678InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
679 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700680
681InputConsumer::~InputConsumer() {
682}
683
684bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600685 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700686}
687
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800688status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
689 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800690 if (DEBUG_TRANSPORT_ACTIONS) {
691 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
692 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
693 }
Jeff Brown5912f952013-07-01 19:10:31 -0700694
695 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700696 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700697
698 // Fetch the next input message.
699 // Loop until an event can be returned or no additional events are received.
700 while (!*outEvent) {
701 if (mMsgDeferred) {
702 // mMsg contains a valid input message from the previous call to consume
703 // that has not yet been processed.
704 mMsgDeferred = false;
705 } else {
706 // Receive a fresh message.
707 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000708 if (result == OK) {
709 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
710 }
Jeff Brown5912f952013-07-01 19:10:31 -0700711 if (result) {
712 // Consume the next batched event unless batches are being held for later.
713 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800714 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700715 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800716 if (DEBUG_TRANSPORT_ACTIONS) {
717 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
718 mChannel->getName().c_str(), *outSeq);
719 }
Jeff Brown5912f952013-07-01 19:10:31 -0700720 break;
721 }
722 }
723 return result;
724 }
725 }
726
727 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700728 case InputMessage::Type::KEY: {
729 KeyEvent* keyEvent = factory->createKeyEvent();
730 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700731
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700732 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500733 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700734 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800735 if (DEBUG_TRANSPORT_ACTIONS) {
736 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
737 mChannel->getName().c_str(), *outSeq);
738 }
Jeff Brown5912f952013-07-01 19:10:31 -0700739 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700740 }
Jeff Brown5912f952013-07-01 19:10:31 -0700741
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700742 case InputMessage::Type::MOTION: {
743 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
744 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500745 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700746 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500747 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800748 if (DEBUG_TRANSPORT_ACTIONS) {
749 ALOGD("channel '%s' consumer ~ appended to batch event",
750 mChannel->getName().c_str());
751 }
Jeff Brown5912f952013-07-01 19:10:31 -0700752 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700753 } else if (isPointerEvent(mMsg.body.motion.source) &&
754 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
755 // No need to process events that we are going to cancel anyways
756 const size_t count = batch.samples.size();
757 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500758 const InputMessage& msg = batch.samples[i];
759 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700760 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500761 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
762 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700763 } else {
764 // We cannot append to the batch in progress, so we need to consume
765 // the previous batch right now and defer the new message until later.
766 mMsgDeferred = true;
767 status_t result = consumeSamples(factory, batch, batch.samples.size(),
768 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500769 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700770 if (result) {
771 return result;
772 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800773 if (DEBUG_TRANSPORT_ACTIONS) {
774 ALOGD("channel '%s' consumer ~ consumed batch event and "
775 "deferred current event, seq=%u",
776 mChannel->getName().c_str(), *outSeq);
777 }
Jeff Brown5912f952013-07-01 19:10:31 -0700778 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700779 }
Jeff Brown5912f952013-07-01 19:10:31 -0700780 }
Jeff Brown5912f952013-07-01 19:10:31 -0700781
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800782 // Start a new batch if needed.
783 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
784 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500785 Batch batch;
786 batch.samples.push_back(mMsg);
787 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800788 if (DEBUG_TRANSPORT_ACTIONS) {
789 ALOGD("channel '%s' consumer ~ started batch event",
790 mChannel->getName().c_str());
791 }
792 break;
793 }
Jeff Brown5912f952013-07-01 19:10:31 -0700794
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800795 MotionEvent* motionEvent = factory->createMotionEvent();
796 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700797
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800798 updateTouchState(mMsg);
799 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500800 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800801 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800802
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800803 if (DEBUG_TRANSPORT_ACTIONS) {
804 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
805 mChannel->getName().c_str(), *outSeq);
806 }
807 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700808 }
Jeff Brown5912f952013-07-01 19:10:31 -0700809
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000810 case InputMessage::Type::FINISHED:
811 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000812 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
813 "InputConsumer!",
814 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800815 break;
816 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800817
818 case InputMessage::Type::FOCUS: {
819 FocusEvent* focusEvent = factory->createFocusEvent();
820 if (!focusEvent) return NO_MEMORY;
821
822 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500823 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800824 *outEvent = focusEvent;
825 break;
826 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800827
828 case InputMessage::Type::CAPTURE: {
829 CaptureEvent* captureEvent = factory->createCaptureEvent();
830 if (!captureEvent) return NO_MEMORY;
831
832 initializeCaptureEvent(captureEvent, &mMsg);
833 *outSeq = mMsg.header.seq;
834 *outEvent = captureEvent;
835 break;
836 }
arthurhung7632c332020-12-30 16:58:01 +0800837
838 case InputMessage::Type::DRAG: {
839 DragEvent* dragEvent = factory->createDragEvent();
840 if (!dragEvent) return NO_MEMORY;
841
842 initializeDragEvent(dragEvent, &mMsg);
843 *outSeq = mMsg.header.seq;
844 *outEvent = dragEvent;
845 break;
846 }
Jeff Brown5912f952013-07-01 19:10:31 -0700847 }
848 }
849 return OK;
850}
851
852status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800853 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700854 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700855 for (size_t i = mBatches.size(); i > 0; ) {
856 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500857 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700858 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800859 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500860 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700861 return result;
862 }
863
Michael Wright32232172013-10-21 12:05:22 -0700864 nsecs_t sampleTime = frameTime;
865 if (mResampleTouch) {
866 sampleTime -= RESAMPLE_LATENCY;
867 }
Jeff Brown5912f952013-07-01 19:10:31 -0700868 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
869 if (split < 0) {
870 continue;
871 }
872
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800873 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700874 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500875 if (batch.samples.empty()) {
876 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700877 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700878 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500879 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700880 }
Michael Wright32232172013-10-21 12:05:22 -0700881 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700882 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
883 }
884 return result;
885 }
886
887 return WOULD_BLOCK;
888}
889
890status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800891 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700892 MotionEvent* motionEvent = factory->createMotionEvent();
893 if (! motionEvent) return NO_MEMORY;
894
895 uint32_t chain = 0;
896 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500897 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100898 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700899 if (i) {
900 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500901 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700902 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500903 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700904 addSample(motionEvent, &msg);
905 } else {
906 initializeMotionEvent(motionEvent, &msg);
907 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500908 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700909 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500910 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700911
912 *outSeq = chain;
913 *outEvent = motionEvent;
914 return OK;
915}
916
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100917void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800918 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700919 return;
920 }
921
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100922 int32_t deviceId = msg.body.motion.deviceId;
923 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700924
925 // Update the touch state history to incorporate the new input message.
926 // If the message is in the past relative to the most recently produced resampled
927 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100928 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700929 case AMOTION_EVENT_ACTION_DOWN: {
930 ssize_t index = findTouchState(deviceId, source);
931 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500932 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700933 index = mTouchStates.size() - 1;
934 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500935 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700936 touchState.initialize(deviceId, source);
937 touchState.addHistory(msg);
938 break;
939 }
940
941 case AMOTION_EVENT_ACTION_MOVE: {
942 ssize_t index = findTouchState(deviceId, source);
943 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500944 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700945 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800946 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700947 }
948 break;
949 }
950
951 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
952 ssize_t index = findTouchState(deviceId, source);
953 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500954 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100955 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700956 rewriteMessage(touchState, msg);
957 }
958 break;
959 }
960
961 case AMOTION_EVENT_ACTION_POINTER_UP: {
962 ssize_t index = findTouchState(deviceId, source);
963 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500964 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700965 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100966 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700967 }
968 break;
969 }
970
971 case AMOTION_EVENT_ACTION_SCROLL: {
972 ssize_t index = findTouchState(deviceId, source);
973 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500974 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700975 rewriteMessage(touchState, msg);
976 }
977 break;
978 }
979
980 case AMOTION_EVENT_ACTION_UP:
981 case AMOTION_EVENT_ACTION_CANCEL: {
982 ssize_t index = findTouchState(deviceId, source);
983 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500984 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700985 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500986 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700987 }
988 break;
989 }
990 }
991}
992
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800993/**
994 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
995 *
996 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
997 * is in the past relative to msg and the past two events do not contain identical coordinates),
998 * then invalidate the lastResample data for that pointer.
999 * If the two past events have identical coordinates, then lastResample data for that pointer will
1000 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1001 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1002 * not equal to x0 is received.
1003 */
1004void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001005 nsecs_t eventTime = msg.body.motion.eventTime;
1006 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1007 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001008 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001009 if (eventTime < state.lastResample.eventTime ||
1010 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001011 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1012 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001013#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001014 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1015 resampleCoords.getX(), resampleCoords.getY(),
1016 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001017#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001018 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1019 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1020 } else {
1021 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001022 }
Jeff Brown5912f952013-07-01 19:10:31 -07001023 }
1024 }
1025}
1026
1027void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1028 const InputMessage* next) {
1029 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001030 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001031 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1032 return;
1033 }
1034
1035 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1036 if (index < 0) {
1037#if DEBUG_RESAMPLING
1038 ALOGD("Not resampled, no touch state for device.");
1039#endif
1040 return;
1041 }
1042
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001043 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001044 if (touchState.historySize < 1) {
1045#if DEBUG_RESAMPLING
1046 ALOGD("Not resampled, no history for device.");
1047#endif
1048 return;
1049 }
1050
1051 // Ensure that the current sample has all of the pointers that need to be reported.
1052 const History* current = touchState.getHistory(0);
1053 size_t pointerCount = event->getPointerCount();
1054 for (size_t i = 0; i < pointerCount; i++) {
1055 uint32_t id = event->getPointerId(i);
1056 if (!current->idBits.hasBit(id)) {
1057#if DEBUG_RESAMPLING
1058 ALOGD("Not resampled, missing id %d", id);
1059#endif
1060 return;
1061 }
1062 }
1063
1064 // Find the data to use for resampling.
1065 const History* other;
1066 History future;
1067 float alpha;
1068 if (next) {
1069 // Interpolate between current sample and future sample.
1070 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001071 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001072 other = &future;
1073 nsecs_t delta = future.eventTime - current->eventTime;
1074 if (delta < RESAMPLE_MIN_DELTA) {
1075#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001076 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001077#endif
1078 return;
1079 }
1080 alpha = float(sampleTime - current->eventTime) / delta;
1081 } else if (touchState.historySize >= 2) {
1082 // Extrapolate future sample using current sample and past sample.
1083 // So other->eventTime <= current->eventTime <= sampleTime.
1084 other = touchState.getHistory(1);
1085 nsecs_t delta = current->eventTime - other->eventTime;
1086 if (delta < RESAMPLE_MIN_DELTA) {
1087#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001088 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001089#endif
1090 return;
1091 } else if (delta > RESAMPLE_MAX_DELTA) {
1092#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001093 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001094#endif
1095 return;
1096 }
1097 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1098 if (sampleTime > maxPredict) {
1099#if DEBUG_RESAMPLING
1100 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001101 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001102 sampleTime - current->eventTime, maxPredict - current->eventTime);
1103#endif
1104 sampleTime = maxPredict;
1105 }
1106 alpha = float(current->eventTime - sampleTime) / delta;
1107 } else {
1108#if DEBUG_RESAMPLING
1109 ALOGD("Not resampled, insufficient data.");
1110#endif
1111 return;
1112 }
1113
1114 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001115 History oldLastResample;
1116 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001117 touchState.lastResample.eventTime = sampleTime;
1118 touchState.lastResample.idBits.clear();
1119 for (size_t i = 0; i < pointerCount; i++) {
1120 uint32_t id = event->getPointerId(i);
1121 touchState.lastResample.idToIndex[id] = i;
1122 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001123 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1124 // We maintain the previously resampled value for this pointer (stored in
1125 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1126 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1127
1128 // We know here that the coordinates for the pointer haven't changed because we
1129 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1130 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1131 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1132 continue;
1133 }
1134
Jeff Brown5912f952013-07-01 19:10:31 -07001135 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1136 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001137 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001138 if (other->idBits.hasBit(id)
1139 && shouldResampleTool(event->getToolType(i))) {
1140 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001141 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1142 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1143 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1144 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1145#if DEBUG_RESAMPLING
1146 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1147 "other (%0.3f, %0.3f), alpha %0.3f",
1148 id, resampledCoords.getX(), resampledCoords.getY(),
1149 currentCoords.getX(), currentCoords.getY(),
1150 otherCoords.getX(), otherCoords.getY(),
1151 alpha);
1152#endif
1153 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001154#if DEBUG_RESAMPLING
1155 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1156 id, resampledCoords.getX(), resampledCoords.getY(),
1157 currentCoords.getX(), currentCoords.getY());
1158#endif
1159 }
1160 }
1161
1162 event->addSample(sampleTime, touchState.lastResample.pointers);
1163}
1164
1165bool InputConsumer::shouldResampleTool(int32_t toolType) {
1166 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1167 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1168}
1169
1170status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001171 if (DEBUG_TRANSPORT_ACTIONS) {
1172 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1173 mChannel->getName().c_str(), seq, toString(handled));
1174 }
Jeff Brown5912f952013-07-01 19:10:31 -07001175
1176 if (!seq) {
1177 ALOGE("Attempted to send a finished signal with sequence number 0.");
1178 return BAD_VALUE;
1179 }
1180
1181 // Send finished signals for the batch sequence chain first.
1182 size_t seqChainCount = mSeqChains.size();
1183 if (seqChainCount) {
1184 uint32_t currentSeq = seq;
1185 uint32_t chainSeqs[seqChainCount];
1186 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001187 for (size_t i = seqChainCount; i > 0; ) {
1188 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001189 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001190 if (seqChain.seq == currentSeq) {
1191 currentSeq = seqChain.chain;
1192 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001193 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001194 }
1195 }
1196 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001197 while (!status && chainIndex > 0) {
1198 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001199 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1200 }
1201 if (status) {
1202 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001203 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001204 SeqChain seqChain;
1205 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1206 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001207 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001208 if (!chainIndex) break;
1209 chainIndex--;
1210 }
Jeff Brown5912f952013-07-01 19:10:31 -07001211 return status;
1212 }
1213 }
1214
1215 // Send finished signal for the last message in the batch.
1216 return sendUnchainedFinishedSignal(seq, handled);
1217}
1218
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001219status_t InputConsumer::sendTimeline(int32_t inputEventId,
1220 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1221 if (DEBUG_TRANSPORT_ACTIONS) {
1222 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1223 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1224 mChannel->getName().c_str(), inputEventId,
1225 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1226 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1227 }
1228
1229 InputMessage msg;
1230 msg.header.type = InputMessage::Type::TIMELINE;
1231 msg.header.seq = 0;
1232 msg.body.timeline.eventId = inputEventId;
1233 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1234 return mChannel->sendMessage(&msg);
1235}
1236
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001237nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1238 auto it = mConsumeTimes.find(seq);
1239 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1240 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1241 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1242 seq);
1243 return it->second;
1244}
1245
1246void InputConsumer::popConsumeTime(uint32_t seq) {
1247 mConsumeTimes.erase(seq);
1248}
1249
Jeff Brown5912f952013-07-01 19:10:31 -07001250status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1251 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001252 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001253 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001254 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001255 msg.body.finished.consumeTime = getConsumeTime(seq);
1256 status_t result = mChannel->sendMessage(&msg);
1257 if (result == OK) {
1258 // Remove the consume time if the socket write succeeded. We will not need to ack this
1259 // message anymore. If the socket write did not succeed, we will try again and will still
1260 // need consume time.
1261 popConsumeTime(seq);
1262 }
1263 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001264}
1265
1266bool InputConsumer::hasDeferredEvent() const {
1267 return mMsgDeferred;
1268}
1269
1270bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001271 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001272}
1273
Arthur Hungc7812be2020-02-27 22:40:27 +08001274int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001275 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001276 return AINPUT_SOURCE_CLASS_NONE;
1277 }
1278
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001279 const Batch& batch = mBatches[0];
1280 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001281 return head.body.motion.source;
1282}
1283
Jeff Brown5912f952013-07-01 19:10:31 -07001284ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1285 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001286 const Batch& batch = mBatches[i];
1287 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001288 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1289 return i;
1290 }
1291 }
1292 return -1;
1293}
1294
1295ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1296 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001297 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001298 if (touchState.deviceId == deviceId && touchState.source == source) {
1299 return i;
1300 }
1301 }
1302 return -1;
1303}
1304
1305void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001306 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001307 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1308 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1309 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1310 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001311}
1312
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001313void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001314 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1315 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001316}
1317
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001318void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001319 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001320}
1321
arthurhung7632c332020-12-30 16:58:01 +08001322void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1323 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1324 msg->body.drag.isExiting);
1325}
1326
Jeff Brown5912f952013-07-01 19:10:31 -07001327void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001328 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001329 PointerProperties pointerProperties[pointerCount];
1330 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001331 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001332 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1333 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1334 }
1335
chaviw9eaa22c2020-07-01 16:21:27 -07001336 ui::Transform transform;
1337 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1338 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001339 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1340 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1341 msg->body.motion.actionButton, msg->body.motion.flags,
1342 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001343 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1344 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1345 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1346 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1347 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001348}
1349
1350void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001351 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001352 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001353 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001354 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1355 }
1356
1357 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1358 event->addSample(msg->body.motion.eventTime, pointerCoords);
1359}
1360
1361bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001362 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001363 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001364 if (head.body.motion.pointerCount != pointerCount
1365 || head.body.motion.action != msg->body.motion.action) {
1366 return false;
1367 }
1368 for (size_t i = 0; i < pointerCount; i++) {
1369 if (head.body.motion.pointers[i].properties
1370 != msg->body.motion.pointers[i].properties) {
1371 return false;
1372 }
1373 }
1374 return true;
1375}
1376
1377ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1378 size_t numSamples = batch.samples.size();
1379 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001380 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001381 index += 1;
1382 }
1383 return ssize_t(index) - 1;
1384}
1385
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001386std::string InputConsumer::dump() const {
1387 std::string out;
1388 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1389 out = out + "mChannel = " + mChannel->getName() + "\n";
1390 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1391 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001392 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001393 }
1394 out += "Batches:\n";
1395 for (const Batch& batch : mBatches) {
1396 out += " Batch:\n";
1397 for (const InputMessage& msg : batch.samples) {
1398 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001399 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001400 switch (msg.header.type) {
1401 case InputMessage::Type::KEY: {
1402 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1403 KeyEvent::actionToString(
1404 msg.body.key.action),
1405 msg.body.key.keyCode);
1406 break;
1407 }
1408 case InputMessage::Type::MOTION: {
1409 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1410 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1411 const float x = msg.body.motion.pointers[i].coords.getX();
1412 const float y = msg.body.motion.pointers[i].coords.getY();
1413 out += android::base::StringPrintf("\n Pointer %" PRIu32
1414 " : x=%.1f y=%.1f",
1415 i, x, y);
1416 }
1417 break;
1418 }
1419 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001420 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1421 toString(msg.body.finished.handled),
1422 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001423 break;
1424 }
1425 case InputMessage::Type::FOCUS: {
1426 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1427 toString(msg.body.focus.hasFocus),
1428 toString(msg.body.focus.inTouchMode));
1429 break;
1430 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001431 case InputMessage::Type::CAPTURE: {
1432 out += android::base::StringPrintf("hasCapture=%s",
1433 toString(msg.body.capture
1434 .pointerCaptureEnabled));
1435 break;
1436 }
arthurhung7632c332020-12-30 16:58:01 +08001437 case InputMessage::Type::DRAG: {
1438 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1439 msg.body.drag.x, msg.body.drag.y,
1440 toString(msg.body.drag.isExiting));
1441 break;
1442 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001443 case InputMessage::Type::TIMELINE: {
1444 const nsecs_t gpuCompletedTime =
1445 msg.body.timeline
1446 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1447 const nsecs_t presentTime =
1448 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1449 out += android::base::StringPrintf("inputEventId=%" PRId32
1450 ", gpuCompletedTime=%" PRId64
1451 ", presentTime=%" PRId64,
1452 msg.body.timeline.eventId, gpuCompletedTime,
1453 presentTime);
1454 break;
1455 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001456 }
1457 out += "\n";
1458 }
1459 }
1460 if (mBatches.empty()) {
1461 out += " <empty>\n";
1462 }
1463 out += "mSeqChains:\n";
1464 for (const SeqChain& chain : mSeqChains) {
1465 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1466 chain.chain);
1467 }
1468 if (mSeqChains.empty()) {
1469 out += " <empty>\n";
1470 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001471 out += "mConsumeTimes:\n";
1472 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1473 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1474 consumeTime);
1475 }
1476 if (mConsumeTimes.empty()) {
1477 out += " <empty>\n";
1478 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001479 return out;
1480}
1481
Jeff Brown5912f952013-07-01 19:10:31 -07001482} // namespace android