blob: 6218fdcac197c6073a4cd047ab59ce9c175e97b2 [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>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080091inline static const char* toString(bool value) {
92 return value ? "true" : "false";
93}
94
Jeff Brown5912f952013-07-01 19:10:31 -070095// --- InputMessage ---
96
97bool InputMessage::isValid(size_t actualSize) const {
98 if (size() == actualSize) {
99 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700100 case Type::KEY:
101 return true;
102 case Type::MOTION:
103 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
104 case Type::FINISHED:
105 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 case Type::FOCUS:
107 return true;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800108 case Type::CAPTURE:
109 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700110 }
111 }
112 return false;
113}
114
115size_t InputMessage::size() const {
116 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700117 case Type::KEY:
118 return sizeof(Header) + body.key.size();
119 case Type::MOTION:
120 return sizeof(Header) + body.motion.size();
121 case Type::FINISHED:
122 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800123 case Type::FOCUS:
124 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800125 case Type::CAPTURE:
126 return sizeof(Header) + body.capture.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700127 }
128 return sizeof(Header);
129}
130
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800131/**
132 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
133 * memory to zero, then only copy the valid bytes on a per-field basis.
134 */
135void InputMessage::getSanitizedCopy(InputMessage* msg) const {
136 memset(msg, 0, sizeof(*msg));
137
138 // Write the header
139 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500140 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800141
142 // Write the body
143 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700144 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800145 // int32_t eventId
146 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800147 // nsecs_t eventTime
148 msg->body.key.eventTime = body.key.eventTime;
149 // int32_t deviceId
150 msg->body.key.deviceId = body.key.deviceId;
151 // int32_t source
152 msg->body.key.source = body.key.source;
153 // int32_t displayId
154 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600155 // std::array<uint8_t, 32> hmac
156 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800157 // int32_t action
158 msg->body.key.action = body.key.action;
159 // int32_t flags
160 msg->body.key.flags = body.key.flags;
161 // int32_t keyCode
162 msg->body.key.keyCode = body.key.keyCode;
163 // int32_t scanCode
164 msg->body.key.scanCode = body.key.scanCode;
165 // int32_t metaState
166 msg->body.key.metaState = body.key.metaState;
167 // int32_t repeatCount
168 msg->body.key.repeatCount = body.key.repeatCount;
169 // nsecs_t downTime
170 msg->body.key.downTime = body.key.downTime;
171 break;
172 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700173 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800174 // int32_t eventId
175 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800176 // nsecs_t eventTime
177 msg->body.motion.eventTime = body.motion.eventTime;
178 // int32_t deviceId
179 msg->body.motion.deviceId = body.motion.deviceId;
180 // int32_t source
181 msg->body.motion.source = body.motion.source;
182 // int32_t displayId
183 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600184 // std::array<uint8_t, 32> hmac
185 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800186 // int32_t action
187 msg->body.motion.action = body.motion.action;
188 // int32_t actionButton
189 msg->body.motion.actionButton = body.motion.actionButton;
190 // int32_t flags
191 msg->body.motion.flags = body.motion.flags;
192 // int32_t metaState
193 msg->body.motion.metaState = body.motion.metaState;
194 // int32_t buttonState
195 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800196 // MotionClassification classification
197 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800198 // int32_t edgeFlags
199 msg->body.motion.edgeFlags = body.motion.edgeFlags;
200 // nsecs_t downTime
201 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700202
203 msg->body.motion.dsdx = body.motion.dsdx;
204 msg->body.motion.dtdx = body.motion.dtdx;
205 msg->body.motion.dtdy = body.motion.dtdy;
206 msg->body.motion.dsdy = body.motion.dsdy;
207 msg->body.motion.tx = body.motion.tx;
208 msg->body.motion.ty = body.motion.ty;
209
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800210 // float xPrecision
211 msg->body.motion.xPrecision = body.motion.xPrecision;
212 // float yPrecision
213 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700214 // float xCursorPosition
215 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
216 // float yCursorPosition
217 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800218 // uint32_t pointerCount
219 msg->body.motion.pointerCount = body.motion.pointerCount;
220 //struct Pointer pointers[MAX_POINTERS]
221 for (size_t i = 0; i < body.motion.pointerCount; i++) {
222 // PointerProperties properties
223 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
224 msg->body.motion.pointers[i].properties.toolType =
225 body.motion.pointers[i].properties.toolType,
226 // PointerCoords coords
227 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
228 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
229 memcpy(&msg->body.motion.pointers[i].coords.values[0],
230 &body.motion.pointers[i].coords.values[0],
231 count * (sizeof(body.motion.pointers[i].coords.values[0])));
232 }
233 break;
234 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700235 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800236 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000237 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800238 break;
239 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800240 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800241 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800242 msg->body.focus.hasFocus = body.focus.hasFocus;
243 msg->body.focus.inTouchMode = body.focus.inTouchMode;
244 break;
245 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800246 case InputMessage::Type::CAPTURE: {
247 msg->body.capture.eventId = body.capture.eventId;
248 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
249 break;
250 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800251 }
252}
Jeff Brown5912f952013-07-01 19:10:31 -0700253
254// --- InputChannel ---
255
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500256std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500257 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700258 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
259 if (result != 0) {
260 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
261 strerror(errno));
262 return nullptr;
263 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500264 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500265 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700266}
267
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500268InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
269 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700270 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500271 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700272 }
Jeff Brown5912f952013-07-01 19:10:31 -0700273}
274
275InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700276 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500277 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700278 }
Robert Carr3720ed02018-08-08 16:08:27 -0700279}
280
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800281status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500282 std::unique_ptr<InputChannel>& outServerChannel,
283 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700284 int sockets[2];
285 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
286 status_t result = -errno;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500287 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d", name.c_str(), errno);
288 outServerChannel.reset();
289 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700290 return result;
291 }
292
293 int bufferSize = SOCKET_BUFFER_SIZE;
294 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
295 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
296 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
297 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
298
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700299 sp<IBinder> token = new BBinder();
300
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700301 std::string serverChannelName = name + " (server)";
302 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700303 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700304
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700305 std::string clientChannelName = name + " (client)";
306 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700307 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700308 return OK;
309}
310
311status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800312 const size_t msgLength = msg->size();
313 InputMessage cleanMsg;
314 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700315 ssize_t nWrite;
316 do {
Chris Ye0783e992020-06-02 21:34:49 -0700317 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700318 } while (nWrite == -1 && errno == EINTR);
319
320 if (nWrite < 0) {
321 int error = errno;
322#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800323 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
324 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700325#endif
326 if (error == EAGAIN || error == EWOULDBLOCK) {
327 return WOULD_BLOCK;
328 }
329 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
330 return DEAD_OBJECT;
331 }
332 return -error;
333 }
334
335 if (size_t(nWrite) != msgLength) {
336#if DEBUG_CHANNEL_MESSAGES
337 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800338 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700339#endif
340 return DEAD_OBJECT;
341 }
342
343#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800344 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700345#endif
346 return OK;
347}
348
349status_t InputChannel::receiveMessage(InputMessage* msg) {
350 ssize_t nRead;
351 do {
Chris Ye0783e992020-06-02 21:34:49 -0700352 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700353 } while (nRead == -1 && errno == EINTR);
354
355 if (nRead < 0) {
356 int error = errno;
357#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800358 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700359#endif
360 if (error == EAGAIN || error == EWOULDBLOCK) {
361 return WOULD_BLOCK;
362 }
363 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
364 return DEAD_OBJECT;
365 }
366 return -error;
367 }
368
369 if (nRead == 0) { // check for EOF
370#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800371 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700372#endif
373 return DEAD_OBJECT;
374 }
375
376 if (!msg->isValid(nRead)) {
377#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800378 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700379#endif
380 return BAD_VALUE;
381 }
382
383#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800384 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700385#endif
386 return OK;
387}
388
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500389std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700390 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700391 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700392}
393
Garfield Tan15601662020-09-22 15:32:38 -0700394void InputChannel::copyTo(InputChannel& outChannel) const {
395 outChannel.mName = getName();
396 outChannel.mFd = dupFd();
397 outChannel.mToken = getConnectionToken();
398}
399
Chris Ye0783e992020-06-02 21:34:49 -0700400status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500401 if (parcel == nullptr) {
402 ALOGE("%s: Null parcel", __func__);
403 return BAD_VALUE;
404 }
405 return parcel->writeStrongBinder(mToken)
406 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700407}
408
Chris Ye0783e992020-06-02 21:34:49 -0700409status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500410 if (parcel == nullptr) {
411 ALOGE("%s: Null parcel", __func__);
412 return BAD_VALUE;
413 }
414 mToken = parcel->readStrongBinder();
415 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700416}
417
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700418sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500419 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700420}
421
Garfield Tan15601662020-09-22 15:32:38 -0700422base::unique_fd InputChannel::dupFd() const {
423 android::base::unique_fd newFd(::dup(getFd()));
424 if (!newFd.ok()) {
425 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
426 strerror(errno));
427 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
428 // If this process is out of file descriptors, then throwing that might end up exploding
429 // on the other side of a binder call, which isn't really helpful.
430 // Better to just crash here and hope that the FD leak is slow.
431 // Other failures could be client errors, so we still propagate those back to the caller.
432 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
433 getName().c_str());
434 return {};
435 }
436 return newFd;
437}
438
Jeff Brown5912f952013-07-01 19:10:31 -0700439// --- InputPublisher ---
440
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500441InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700442
443InputPublisher::~InputPublisher() {
444}
445
Garfield Tan1c7bc862020-01-28 13:24:04 -0800446status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
447 int32_t source, int32_t displayId,
448 std::array<uint8_t, 32> hmac, int32_t action,
449 int32_t flags, int32_t keyCode, int32_t scanCode,
450 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
451 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000452 if (ATRACE_ENABLED()) {
453 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
454 mChannel->getName().c_str(), keyCode);
455 ATRACE_NAME(message.c_str());
456 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800457 if (DEBUG_TRANSPORT_ACTIONS) {
458 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
459 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
460 "downTime=%" PRId64 ", eventTime=%" PRId64,
461 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
462 metaState, repeatCount, downTime, eventTime);
463 }
Jeff Brown5912f952013-07-01 19:10:31 -0700464
465 if (!seq) {
466 ALOGE("Attempted to publish a key event with sequence number 0.");
467 return BAD_VALUE;
468 }
469
470 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700471 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500472 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800473 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700474 msg.body.key.deviceId = deviceId;
475 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100476 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700477 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700478 msg.body.key.action = action;
479 msg.body.key.flags = flags;
480 msg.body.key.keyCode = keyCode;
481 msg.body.key.scanCode = scanCode;
482 msg.body.key.metaState = metaState;
483 msg.body.key.repeatCount = repeatCount;
484 msg.body.key.downTime = downTime;
485 msg.body.key.eventTime = eventTime;
486 return mChannel->sendMessage(&msg);
487}
488
489status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800490 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600491 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
492 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700493 MotionClassification classification, const ui::Transform& transform, float xPrecision,
494 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
495 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
496 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000497 if (ATRACE_ENABLED()) {
498 std::string message = StringPrintf(
499 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
500 mChannel->getName().c_str(), action);
501 ATRACE_NAME(message.c_str());
502 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800503 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700504 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700505 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800506 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
507 "displayId=%" PRId32 ", "
508 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700509 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800510 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700511 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800512 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
513 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700514 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
515 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800516 }
Jeff Brown5912f952013-07-01 19:10:31 -0700517
518 if (!seq) {
519 ALOGE("Attempted to publish a motion event with sequence number 0.");
520 return BAD_VALUE;
521 }
522
523 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700524 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800525 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700526 return BAD_VALUE;
527 }
528
529 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700530 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500531 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800532 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700533 msg.body.motion.deviceId = deviceId;
534 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700535 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700536 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700537 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100538 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700539 msg.body.motion.flags = flags;
540 msg.body.motion.edgeFlags = edgeFlags;
541 msg.body.motion.metaState = metaState;
542 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800543 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700544 msg.body.motion.dsdx = transform.dsdx();
545 msg.body.motion.dtdx = transform.dtdx();
546 msg.body.motion.dtdy = transform.dtdy();
547 msg.body.motion.dsdy = transform.dsdy();
548 msg.body.motion.tx = transform.tx();
549 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700550 msg.body.motion.xPrecision = xPrecision;
551 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700552 msg.body.motion.xCursorPosition = xCursorPosition;
553 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700554 msg.body.motion.downTime = downTime;
555 msg.body.motion.eventTime = eventTime;
556 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100557 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700558 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
559 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
560 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700561
Jeff Brown5912f952013-07-01 19:10:31 -0700562 return mChannel->sendMessage(&msg);
563}
564
Garfield Tan1c7bc862020-01-28 13:24:04 -0800565status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
566 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800567 if (ATRACE_ENABLED()) {
568 std::string message =
569 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
570 mChannel->getName().c_str(), toString(hasFocus),
571 toString(inTouchMode));
572 ATRACE_NAME(message.c_str());
573 }
574
575 InputMessage msg;
576 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500577 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800578 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800579 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
580 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
581 return mChannel->sendMessage(&msg);
582}
583
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800584status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
585 bool pointerCaptureEnabled) {
586 if (ATRACE_ENABLED()) {
587 std::string message =
588 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
589 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
590 ATRACE_NAME(message.c_str());
591 }
592
593 InputMessage msg;
594 msg.header.type = InputMessage::Type::CAPTURE;
595 msg.header.seq = seq;
596 msg.body.capture.eventId = eventId;
597 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled ? 1 : 0;
598 return mChannel->sendMessage(&msg);
599}
600
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000601status_t InputPublisher::receiveFinishedSignal(
602 const std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)>& callback) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800603 if (DEBUG_TRANSPORT_ACTIONS) {
604 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
605 }
Jeff Brown5912f952013-07-01 19:10:31 -0700606
607 InputMessage msg;
608 status_t result = mChannel->receiveMessage(&msg);
609 if (result) {
Jeff Brown5912f952013-07-01 19:10:31 -0700610 return result;
611 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700612 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700613 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800614 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700615 return UNKNOWN_ERROR;
616 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000617 callback(msg.header.seq, msg.body.finished.handled == 1, msg.body.finished.consumeTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700618 return OK;
619}
620
621// --- InputConsumer ---
622
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500623InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
624 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700625
626InputConsumer::~InputConsumer() {
627}
628
629bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600630 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700631}
632
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800633status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
634 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800635 if (DEBUG_TRANSPORT_ACTIONS) {
636 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
637 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
638 }
Jeff Brown5912f952013-07-01 19:10:31 -0700639
640 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700641 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700642
643 // Fetch the next input message.
644 // Loop until an event can be returned or no additional events are received.
645 while (!*outEvent) {
646 if (mMsgDeferred) {
647 // mMsg contains a valid input message from the previous call to consume
648 // that has not yet been processed.
649 mMsgDeferred = false;
650 } else {
651 // Receive a fresh message.
652 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000653 if (result == OK) {
654 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
655 }
Jeff Brown5912f952013-07-01 19:10:31 -0700656 if (result) {
657 // Consume the next batched event unless batches are being held for later.
658 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800659 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700660 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800661 if (DEBUG_TRANSPORT_ACTIONS) {
662 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
663 mChannel->getName().c_str(), *outSeq);
664 }
Jeff Brown5912f952013-07-01 19:10:31 -0700665 break;
666 }
667 }
668 return result;
669 }
670 }
671
672 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700673 case InputMessage::Type::KEY: {
674 KeyEvent* keyEvent = factory->createKeyEvent();
675 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700676
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700677 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500678 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700679 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800680 if (DEBUG_TRANSPORT_ACTIONS) {
681 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
682 mChannel->getName().c_str(), *outSeq);
683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700685 }
Jeff Brown5912f952013-07-01 19:10:31 -0700686
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700687 case InputMessage::Type::MOTION: {
688 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
689 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500690 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700691 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500692 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800693 if (DEBUG_TRANSPORT_ACTIONS) {
694 ALOGD("channel '%s' consumer ~ appended to batch event",
695 mChannel->getName().c_str());
696 }
Jeff Brown5912f952013-07-01 19:10:31 -0700697 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700698 } else if (isPointerEvent(mMsg.body.motion.source) &&
699 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
700 // No need to process events that we are going to cancel anyways
701 const size_t count = batch.samples.size();
702 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500703 const InputMessage& msg = batch.samples[i];
704 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700705 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500706 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
707 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700708 } else {
709 // We cannot append to the batch in progress, so we need to consume
710 // the previous batch right now and defer the new message until later.
711 mMsgDeferred = true;
712 status_t result = consumeSamples(factory, batch, batch.samples.size(),
713 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500714 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700715 if (result) {
716 return result;
717 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800718 if (DEBUG_TRANSPORT_ACTIONS) {
719 ALOGD("channel '%s' consumer ~ consumed batch event and "
720 "deferred current event, seq=%u",
721 mChannel->getName().c_str(), *outSeq);
722 }
Jeff Brown5912f952013-07-01 19:10:31 -0700723 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700724 }
Jeff Brown5912f952013-07-01 19:10:31 -0700725 }
Jeff Brown5912f952013-07-01 19:10:31 -0700726
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800727 // Start a new batch if needed.
728 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
729 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500730 Batch batch;
731 batch.samples.push_back(mMsg);
732 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800733 if (DEBUG_TRANSPORT_ACTIONS) {
734 ALOGD("channel '%s' consumer ~ started batch event",
735 mChannel->getName().c_str());
736 }
737 break;
738 }
Jeff Brown5912f952013-07-01 19:10:31 -0700739
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800740 MotionEvent* motionEvent = factory->createMotionEvent();
741 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700742
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800743 updateTouchState(mMsg);
744 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500745 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800746 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800747
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800748 if (DEBUG_TRANSPORT_ACTIONS) {
749 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
750 mChannel->getName().c_str(), *outSeq);
751 }
752 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700753 }
Jeff Brown5912f952013-07-01 19:10:31 -0700754
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800755 case InputMessage::Type::FINISHED: {
756 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
757 "InputConsumer!");
758 break;
759 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800760
761 case InputMessage::Type::FOCUS: {
762 FocusEvent* focusEvent = factory->createFocusEvent();
763 if (!focusEvent) return NO_MEMORY;
764
765 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500766 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800767 *outEvent = focusEvent;
768 break;
769 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800770
771 case InputMessage::Type::CAPTURE: {
772 CaptureEvent* captureEvent = factory->createCaptureEvent();
773 if (!captureEvent) return NO_MEMORY;
774
775 initializeCaptureEvent(captureEvent, &mMsg);
776 *outSeq = mMsg.header.seq;
777 *outEvent = captureEvent;
778 break;
779 }
Jeff Brown5912f952013-07-01 19:10:31 -0700780 }
781 }
782 return OK;
783}
784
785status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800786 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700787 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700788 for (size_t i = mBatches.size(); i > 0; ) {
789 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500790 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700791 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800792 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500793 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700794 return result;
795 }
796
Michael Wright32232172013-10-21 12:05:22 -0700797 nsecs_t sampleTime = frameTime;
798 if (mResampleTouch) {
799 sampleTime -= RESAMPLE_LATENCY;
800 }
Jeff Brown5912f952013-07-01 19:10:31 -0700801 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
802 if (split < 0) {
803 continue;
804 }
805
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800806 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700807 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500808 if (batch.samples.empty()) {
809 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700810 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700811 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500812 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700813 }
Michael Wright32232172013-10-21 12:05:22 -0700814 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700815 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
816 }
817 return result;
818 }
819
820 return WOULD_BLOCK;
821}
822
823status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800824 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700825 MotionEvent* motionEvent = factory->createMotionEvent();
826 if (! motionEvent) return NO_MEMORY;
827
828 uint32_t chain = 0;
829 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500830 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100831 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700832 if (i) {
833 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500834 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700835 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500836 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700837 addSample(motionEvent, &msg);
838 } else {
839 initializeMotionEvent(motionEvent, &msg);
840 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500841 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700842 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500843 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700844
845 *outSeq = chain;
846 *outEvent = motionEvent;
847 return OK;
848}
849
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100850void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800851 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700852 return;
853 }
854
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100855 int32_t deviceId = msg.body.motion.deviceId;
856 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700857
858 // Update the touch state history to incorporate the new input message.
859 // If the message is in the past relative to the most recently produced resampled
860 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100861 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700862 case AMOTION_EVENT_ACTION_DOWN: {
863 ssize_t index = findTouchState(deviceId, source);
864 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500865 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700866 index = mTouchStates.size() - 1;
867 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500868 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700869 touchState.initialize(deviceId, source);
870 touchState.addHistory(msg);
871 break;
872 }
873
874 case AMOTION_EVENT_ACTION_MOVE: {
875 ssize_t index = findTouchState(deviceId, source);
876 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500877 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700878 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800879 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700880 }
881 break;
882 }
883
884 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
885 ssize_t index = findTouchState(deviceId, source);
886 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500887 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100888 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700889 rewriteMessage(touchState, msg);
890 }
891 break;
892 }
893
894 case AMOTION_EVENT_ACTION_POINTER_UP: {
895 ssize_t index = findTouchState(deviceId, source);
896 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500897 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700898 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100899 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700900 }
901 break;
902 }
903
904 case AMOTION_EVENT_ACTION_SCROLL: {
905 ssize_t index = findTouchState(deviceId, source);
906 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500907 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700908 rewriteMessage(touchState, msg);
909 }
910 break;
911 }
912
913 case AMOTION_EVENT_ACTION_UP:
914 case AMOTION_EVENT_ACTION_CANCEL: {
915 ssize_t index = findTouchState(deviceId, source);
916 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500917 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700918 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500919 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700920 }
921 break;
922 }
923 }
924}
925
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800926/**
927 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
928 *
929 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
930 * is in the past relative to msg and the past two events do not contain identical coordinates),
931 * then invalidate the lastResample data for that pointer.
932 * If the two past events have identical coordinates, then lastResample data for that pointer will
933 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
934 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
935 * not equal to x0 is received.
936 */
937void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100938 nsecs_t eventTime = msg.body.motion.eventTime;
939 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
940 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700941 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100942 if (eventTime < state.lastResample.eventTime ||
943 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800944 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
945 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700946#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100947 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
948 resampleCoords.getX(), resampleCoords.getY(),
949 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700950#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800951 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
952 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
953 } else {
954 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100955 }
Jeff Brown5912f952013-07-01 19:10:31 -0700956 }
957 }
958}
959
960void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
961 const InputMessage* next) {
962 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800963 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700964 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
965 return;
966 }
967
968 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
969 if (index < 0) {
970#if DEBUG_RESAMPLING
971 ALOGD("Not resampled, no touch state for device.");
972#endif
973 return;
974 }
975
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500976 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700977 if (touchState.historySize < 1) {
978#if DEBUG_RESAMPLING
979 ALOGD("Not resampled, no history for device.");
980#endif
981 return;
982 }
983
984 // Ensure that the current sample has all of the pointers that need to be reported.
985 const History* current = touchState.getHistory(0);
986 size_t pointerCount = event->getPointerCount();
987 for (size_t i = 0; i < pointerCount; i++) {
988 uint32_t id = event->getPointerId(i);
989 if (!current->idBits.hasBit(id)) {
990#if DEBUG_RESAMPLING
991 ALOGD("Not resampled, missing id %d", id);
992#endif
993 return;
994 }
995 }
996
997 // Find the data to use for resampling.
998 const History* other;
999 History future;
1000 float alpha;
1001 if (next) {
1002 // Interpolate between current sample and future sample.
1003 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001004 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001005 other = &future;
1006 nsecs_t delta = future.eventTime - current->eventTime;
1007 if (delta < RESAMPLE_MIN_DELTA) {
1008#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001009 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001010#endif
1011 return;
1012 }
1013 alpha = float(sampleTime - current->eventTime) / delta;
1014 } else if (touchState.historySize >= 2) {
1015 // Extrapolate future sample using current sample and past sample.
1016 // So other->eventTime <= current->eventTime <= sampleTime.
1017 other = touchState.getHistory(1);
1018 nsecs_t delta = current->eventTime - other->eventTime;
1019 if (delta < RESAMPLE_MIN_DELTA) {
1020#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001021 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001022#endif
1023 return;
1024 } else if (delta > RESAMPLE_MAX_DELTA) {
1025#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001026 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001027#endif
1028 return;
1029 }
1030 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1031 if (sampleTime > maxPredict) {
1032#if DEBUG_RESAMPLING
1033 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001034 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001035 sampleTime - current->eventTime, maxPredict - current->eventTime);
1036#endif
1037 sampleTime = maxPredict;
1038 }
1039 alpha = float(current->eventTime - sampleTime) / delta;
1040 } else {
1041#if DEBUG_RESAMPLING
1042 ALOGD("Not resampled, insufficient data.");
1043#endif
1044 return;
1045 }
1046
1047 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001048 History oldLastResample;
1049 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001050 touchState.lastResample.eventTime = sampleTime;
1051 touchState.lastResample.idBits.clear();
1052 for (size_t i = 0; i < pointerCount; i++) {
1053 uint32_t id = event->getPointerId(i);
1054 touchState.lastResample.idToIndex[id] = i;
1055 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001056 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1057 // We maintain the previously resampled value for this pointer (stored in
1058 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1059 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1060
1061 // We know here that the coordinates for the pointer haven't changed because we
1062 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1063 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1064 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1065 continue;
1066 }
1067
Jeff Brown5912f952013-07-01 19:10:31 -07001068 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1069 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001070 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001071 if (other->idBits.hasBit(id)
1072 && shouldResampleTool(event->getToolType(i))) {
1073 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001074 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1075 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1076 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1077 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1078#if DEBUG_RESAMPLING
1079 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1080 "other (%0.3f, %0.3f), alpha %0.3f",
1081 id, resampledCoords.getX(), resampledCoords.getY(),
1082 currentCoords.getX(), currentCoords.getY(),
1083 otherCoords.getX(), otherCoords.getY(),
1084 alpha);
1085#endif
1086 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001087#if DEBUG_RESAMPLING
1088 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1089 id, resampledCoords.getX(), resampledCoords.getY(),
1090 currentCoords.getX(), currentCoords.getY());
1091#endif
1092 }
1093 }
1094
1095 event->addSample(sampleTime, touchState.lastResample.pointers);
1096}
1097
1098bool InputConsumer::shouldResampleTool(int32_t toolType) {
1099 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1100 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1101}
1102
1103status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001104 if (DEBUG_TRANSPORT_ACTIONS) {
1105 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1106 mChannel->getName().c_str(), seq, toString(handled));
1107 }
Jeff Brown5912f952013-07-01 19:10:31 -07001108
1109 if (!seq) {
1110 ALOGE("Attempted to send a finished signal with sequence number 0.");
1111 return BAD_VALUE;
1112 }
1113
1114 // Send finished signals for the batch sequence chain first.
1115 size_t seqChainCount = mSeqChains.size();
1116 if (seqChainCount) {
1117 uint32_t currentSeq = seq;
1118 uint32_t chainSeqs[seqChainCount];
1119 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001120 for (size_t i = seqChainCount; i > 0; ) {
1121 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001122 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001123 if (seqChain.seq == currentSeq) {
1124 currentSeq = seqChain.chain;
1125 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001126 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001127 }
1128 }
1129 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001130 while (!status && chainIndex > 0) {
1131 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001132 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1133 }
1134 if (status) {
1135 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001136 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001137 SeqChain seqChain;
1138 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1139 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001140 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001141 if (!chainIndex) break;
1142 chainIndex--;
1143 }
Jeff Brown5912f952013-07-01 19:10:31 -07001144 return status;
1145 }
1146 }
1147
1148 // Send finished signal for the last message in the batch.
1149 return sendUnchainedFinishedSignal(seq, handled);
1150}
1151
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001152nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1153 auto it = mConsumeTimes.find(seq);
1154 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1155 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1156 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1157 seq);
1158 return it->second;
1159}
1160
1161void InputConsumer::popConsumeTime(uint32_t seq) {
1162 mConsumeTimes.erase(seq);
1163}
1164
Jeff Brown5912f952013-07-01 19:10:31 -07001165status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1166 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001167 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001168 msg.header.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001169 msg.body.finished.handled = handled ? 1 : 0;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001170 msg.body.finished.consumeTime = getConsumeTime(seq);
1171 status_t result = mChannel->sendMessage(&msg);
1172 if (result == OK) {
1173 // Remove the consume time if the socket write succeeded. We will not need to ack this
1174 // message anymore. If the socket write did not succeed, we will try again and will still
1175 // need consume time.
1176 popConsumeTime(seq);
1177 }
1178 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001179}
1180
1181bool InputConsumer::hasDeferredEvent() const {
1182 return mMsgDeferred;
1183}
1184
1185bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001186 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001187}
1188
Arthur Hungc7812be2020-02-27 22:40:27 +08001189int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001190 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001191 return AINPUT_SOURCE_CLASS_NONE;
1192 }
1193
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001194 const Batch& batch = mBatches[0];
1195 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001196 return head.body.motion.source;
1197}
1198
Jeff Brown5912f952013-07-01 19:10:31 -07001199ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1200 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001201 const Batch& batch = mBatches[i];
1202 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001203 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1204 return i;
1205 }
1206 }
1207 return -1;
1208}
1209
1210ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1211 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001212 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001213 if (touchState.deviceId == deviceId && touchState.source == source) {
1214 return i;
1215 }
1216 }
1217 return -1;
1218}
1219
1220void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001221 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001222 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1223 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1224 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1225 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001226}
1227
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001228void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001229 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001230 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001231}
1232
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001233void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
1234 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled == 1);
1235}
1236
Jeff Brown5912f952013-07-01 19:10:31 -07001237void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001238 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001239 PointerProperties pointerProperties[pointerCount];
1240 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001241 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001242 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1243 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1244 }
1245
chaviw9eaa22c2020-07-01 16:21:27 -07001246 ui::Transform transform;
1247 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1248 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001249 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1250 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1251 msg->body.motion.actionButton, msg->body.motion.flags,
1252 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001253 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1254 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1255 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1256 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1257 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001258}
1259
1260void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001261 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001262 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001263 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001264 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1265 }
1266
1267 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1268 event->addSample(msg->body.motion.eventTime, pointerCoords);
1269}
1270
1271bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001272 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001273 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001274 if (head.body.motion.pointerCount != pointerCount
1275 || head.body.motion.action != msg->body.motion.action) {
1276 return false;
1277 }
1278 for (size_t i = 0; i < pointerCount; i++) {
1279 if (head.body.motion.pointers[i].properties
1280 != msg->body.motion.pointers[i].properties) {
1281 return false;
1282 }
1283 }
1284 return true;
1285}
1286
1287ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1288 size_t numSamples = batch.samples.size();
1289 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001290 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001291 index += 1;
1292 }
1293 return ssize_t(index) - 1;
1294}
1295
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001296std::string InputConsumer::dump() const {
1297 std::string out;
1298 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1299 out = out + "mChannel = " + mChannel->getName() + "\n";
1300 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1301 if (mMsgDeferred) {
1302 out = out + "mMsg : " + InputMessage::typeToString(mMsg.header.type) + "\n";
1303 }
1304 out += "Batches:\n";
1305 for (const Batch& batch : mBatches) {
1306 out += " Batch:\n";
1307 for (const InputMessage& msg : batch.samples) {
1308 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1309 InputMessage::typeToString(msg.header.type));
1310 switch (msg.header.type) {
1311 case InputMessage::Type::KEY: {
1312 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1313 KeyEvent::actionToString(
1314 msg.body.key.action),
1315 msg.body.key.keyCode);
1316 break;
1317 }
1318 case InputMessage::Type::MOTION: {
1319 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1320 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1321 const float x = msg.body.motion.pointers[i].coords.getX();
1322 const float y = msg.body.motion.pointers[i].coords.getY();
1323 out += android::base::StringPrintf("\n Pointer %" PRIu32
1324 " : x=%.1f y=%.1f",
1325 i, x, y);
1326 }
1327 break;
1328 }
1329 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001330 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1331 toString(msg.body.finished.handled),
1332 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001333 break;
1334 }
1335 case InputMessage::Type::FOCUS: {
1336 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1337 toString(msg.body.focus.hasFocus),
1338 toString(msg.body.focus.inTouchMode));
1339 break;
1340 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001341 case InputMessage::Type::CAPTURE: {
1342 out += android::base::StringPrintf("hasCapture=%s",
1343 toString(msg.body.capture
1344 .pointerCaptureEnabled));
1345 break;
1346 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001347 }
1348 out += "\n";
1349 }
1350 }
1351 if (mBatches.empty()) {
1352 out += " <empty>\n";
1353 }
1354 out += "mSeqChains:\n";
1355 for (const SeqChain& chain : mSeqChains) {
1356 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1357 chain.chain);
1358 }
1359 if (mSeqChains.empty()) {
1360 out += " <empty>\n";
1361 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001362 out += "mConsumeTimes:\n";
1363 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1364 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1365 consumeTime);
1366 }
1367 if (mConsumeTimes.empty()) {
1368 out += " <empty>\n";
1369 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001370 return out;
1371}
1372
Jeff Brown5912f952013-07-01 19:10:31 -07001373} // namespace android