blob: bdbd70818656e5a411b8d63fda578bcc44456552 [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
Jeff Brown5912f952013-07-01 19:10:31 -07008#include <errno.h>
9#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070010#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070011#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070012#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070013#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070014#include <unistd.h>
15
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000016#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000017#include <android-base/stringprintf.h>
18#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070019#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080020#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070021#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000022#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070023
Jeff Brown5912f952013-07-01 19:10:31 -070024#include <input/InputTransport.h>
25
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000026namespace {
27
28/**
29 * Log debug messages about channel messages (send message, receive message).
30 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
31 * (requires restart)
32 */
33const bool DEBUG_CHANNEL_MESSAGES =
34 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
35
36/**
37 * Log debug messages whenever InputChannel objects are created/destroyed.
38 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
39 * (requires restart)
40 */
41const bool DEBUG_CHANNEL_LIFECYCLE =
42 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
43
44/**
45 * Log debug messages relating to the consumer end of the transport channel.
46 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
47 */
48
49const bool DEBUG_TRANSPORT_CONSUMER =
50 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
51
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000052const bool IS_DEBUGGABLE_BUILD =
53#if defined(__ANDROID__)
54 android::base::GetBoolProperty("ro.debuggable", false);
55#else
56 true;
57#endif
58
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000059/**
60 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000061 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
62 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
63 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000064 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000065bool debugTransportPublisher() {
66 if (!IS_DEBUGGABLE_BUILD) {
67 static const bool DEBUG_TRANSPORT_PUBLISHER =
68 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
69 return DEBUG_TRANSPORT_PUBLISHER;
70 }
71 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
72}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000073
74/**
75 * Log debug messages about touch event resampling.
76 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG" (requires restart)
77 */
78const bool DEBUG_RESAMPLING =
79 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
80
81} // namespace
82
Michael Wright3dd60e22019-03-27 22:06:44 +000083using android::base::StringPrintf;
84
Jeff Brown5912f952013-07-01 19:10:31 -070085namespace android {
86
87// Socket buffer size. The default is typically about 128KB, which is much larger than
88// we really need. So we make it smaller. It just needs to be big enough to hold
89// a few dozen large multi-finger motion events in the case where an application gets
90// behind processing touches.
91static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
92
93// Nanoseconds per milliseconds.
94static const nsecs_t NANOS_PER_MS = 1000000;
95
96// Latency added during resampling. A few milliseconds doesn't hurt much but
97// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -080098const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -070099
100// Minimum time difference between consecutive samples before attempting to resample.
101static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
102
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700103// Maximum time difference between consecutive samples before attempting to resample
104// by extrapolation.
105static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
106
Jeff Brown5912f952013-07-01 19:10:31 -0700107// Maximum time to predict forward from the last known state, to avoid predicting too
108// far into the future. This time is further bounded by 50% of the last time delta.
109static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
110
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600111/**
112 * System property for enabling / disabling touch resampling.
113 * Resampling extrapolates / interpolates the reported touch event coordinates to better
114 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
115 * Resampling is not needed (and should be disabled) on hardware that already
116 * has touch events triggered by VSYNC.
117 * Set to "1" to enable resampling (default).
118 * Set to "0" to disable resampling.
119 * Resampling is enabled by default.
120 */
121static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
122
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800123/**
124 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
125 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
126 */
127static bool verifyEvents() {
128 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
129}
130
Jeff Brown5912f952013-07-01 19:10:31 -0700131template<typename T>
132inline static T min(const T& a, const T& b) {
133 return a < b ? a : b;
134}
135
136inline static float lerp(float a, float b, float alpha) {
137 return a + alpha * (b - a);
138}
139
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800140inline static bool isPointerEvent(int32_t source) {
141 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
142}
143
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800144inline static const char* toString(bool value) {
145 return value ? "true" : "false";
146}
147
Jeff Brown5912f952013-07-01 19:10:31 -0700148// --- InputMessage ---
149
150bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000151 if (size() != actualSize) {
152 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
153 return false;
154 }
155
156 switch (header.type) {
157 case Type::KEY:
158 return true;
159 case Type::MOTION: {
160 const bool valid =
161 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
162 if (!valid) {
163 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
164 }
165 return valid;
166 }
167 case Type::FINISHED:
168 case Type::FOCUS:
169 case Type::CAPTURE:
170 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700171 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000172 return true;
173 case Type::TIMELINE: {
174 const nsecs_t gpuCompletedTime =
175 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
176 const nsecs_t presentTime =
177 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
178 const bool valid = presentTime > gpuCompletedTime;
179 if (!valid) {
180 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
181 " presentTime = %" PRId64,
182 gpuCompletedTime, presentTime);
183 }
184 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700185 }
186 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000187 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700188 return false;
189}
190
191size_t InputMessage::size() const {
192 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700193 case Type::KEY:
194 return sizeof(Header) + body.key.size();
195 case Type::MOTION:
196 return sizeof(Header) + body.motion.size();
197 case Type::FINISHED:
198 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800199 case Type::FOCUS:
200 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800201 case Type::CAPTURE:
202 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800203 case Type::DRAG:
204 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000205 case Type::TIMELINE:
206 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700207 case Type::TOUCH_MODE:
208 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700209 }
210 return sizeof(Header);
211}
212
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800213/**
214 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
215 * memory to zero, then only copy the valid bytes on a per-field basis.
216 */
217void InputMessage::getSanitizedCopy(InputMessage* msg) const {
218 memset(msg, 0, sizeof(*msg));
219
220 // Write the header
221 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500222 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223
224 // Write the body
225 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700226 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800227 // int32_t eventId
228 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800229 // nsecs_t eventTime
230 msg->body.key.eventTime = body.key.eventTime;
231 // int32_t deviceId
232 msg->body.key.deviceId = body.key.deviceId;
233 // int32_t source
234 msg->body.key.source = body.key.source;
235 // int32_t displayId
236 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600237 // std::array<uint8_t, 32> hmac
238 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800239 // int32_t action
240 msg->body.key.action = body.key.action;
241 // int32_t flags
242 msg->body.key.flags = body.key.flags;
243 // int32_t keyCode
244 msg->body.key.keyCode = body.key.keyCode;
245 // int32_t scanCode
246 msg->body.key.scanCode = body.key.scanCode;
247 // int32_t metaState
248 msg->body.key.metaState = body.key.metaState;
249 // int32_t repeatCount
250 msg->body.key.repeatCount = body.key.repeatCount;
251 // nsecs_t downTime
252 msg->body.key.downTime = body.key.downTime;
253 break;
254 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700255 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800256 // int32_t eventId
257 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700258 // uint32_t pointerCount
259 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800260 // nsecs_t eventTime
261 msg->body.motion.eventTime = body.motion.eventTime;
262 // int32_t deviceId
263 msg->body.motion.deviceId = body.motion.deviceId;
264 // int32_t source
265 msg->body.motion.source = body.motion.source;
266 // int32_t displayId
267 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600268 // std::array<uint8_t, 32> hmac
269 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800270 // int32_t action
271 msg->body.motion.action = body.motion.action;
272 // int32_t actionButton
273 msg->body.motion.actionButton = body.motion.actionButton;
274 // int32_t flags
275 msg->body.motion.flags = body.motion.flags;
276 // int32_t metaState
277 msg->body.motion.metaState = body.motion.metaState;
278 // int32_t buttonState
279 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800280 // MotionClassification classification
281 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800282 // int32_t edgeFlags
283 msg->body.motion.edgeFlags = body.motion.edgeFlags;
284 // nsecs_t downTime
285 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700286
287 msg->body.motion.dsdx = body.motion.dsdx;
288 msg->body.motion.dtdx = body.motion.dtdx;
289 msg->body.motion.dtdy = body.motion.dtdy;
290 msg->body.motion.dsdy = body.motion.dsdy;
291 msg->body.motion.tx = body.motion.tx;
292 msg->body.motion.ty = body.motion.ty;
293
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800294 // float xPrecision
295 msg->body.motion.xPrecision = body.motion.xPrecision;
296 // float yPrecision
297 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700298 // float xCursorPosition
299 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
300 // float yCursorPosition
301 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700302
303 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
304 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
305 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
306 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
307 msg->body.motion.txRaw = body.motion.txRaw;
308 msg->body.motion.tyRaw = body.motion.tyRaw;
309
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800310 //struct Pointer pointers[MAX_POINTERS]
311 for (size_t i = 0; i < body.motion.pointerCount; i++) {
312 // PointerProperties properties
313 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
314 msg->body.motion.pointers[i].properties.toolType =
315 body.motion.pointers[i].properties.toolType,
316 // PointerCoords coords
317 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
318 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
319 memcpy(&msg->body.motion.pointers[i].coords.values[0],
320 &body.motion.pointers[i].coords.values[0],
321 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800322 msg->body.motion.pointers[i].coords.isResampled =
323 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800324 }
325 break;
326 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700327 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800328 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000329 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800330 break;
331 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800332 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800333 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800334 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800335 break;
336 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800337 case InputMessage::Type::CAPTURE: {
338 msg->body.capture.eventId = body.capture.eventId;
339 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
340 break;
341 }
arthurhung7632c332020-12-30 16:58:01 +0800342 case InputMessage::Type::DRAG: {
343 msg->body.drag.eventId = body.drag.eventId;
344 msg->body.drag.x = body.drag.x;
345 msg->body.drag.y = body.drag.y;
346 msg->body.drag.isExiting = body.drag.isExiting;
347 break;
348 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000349 case InputMessage::Type::TIMELINE: {
350 msg->body.timeline.eventId = body.timeline.eventId;
351 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
352 break;
353 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700354 case InputMessage::Type::TOUCH_MODE: {
355 msg->body.touchMode.eventId = body.touchMode.eventId;
356 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
357 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800358 }
359}
Jeff Brown5912f952013-07-01 19:10:31 -0700360
361// --- InputChannel ---
362
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500363std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500364 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700365 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
366 if (result != 0) {
367 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
368 strerror(errno));
369 return nullptr;
370 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500371 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500372 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700373}
374
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500375InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
376 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000377 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
378 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700379}
380
381InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000382 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
383 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700384}
385
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800386status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500387 std::unique_ptr<InputChannel>& outServerChannel,
388 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700389 int sockets[2];
390 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
391 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000392 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
393 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500394 outServerChannel.reset();
395 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700396 return result;
397 }
398
399 int bufferSize = SOCKET_BUFFER_SIZE;
400 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
401 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
402 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
403 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
404
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700405 sp<IBinder> token = new BBinder();
406
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700407 std::string serverChannelName = name + " (server)";
408 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700409 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700410
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700411 std::string clientChannelName = name + " (client)";
412 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700413 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700414 return OK;
415}
416
417status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800418 const size_t msgLength = msg->size();
419 InputMessage cleanMsg;
420 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700421 ssize_t nWrite;
422 do {
Chris Ye0783e992020-06-02 21:34:49 -0700423 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700424 } while (nWrite == -1 && errno == EINTR);
425
426 if (nWrite < 0) {
427 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000428 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
429 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700430 if (error == EAGAIN || error == EWOULDBLOCK) {
431 return WOULD_BLOCK;
432 }
433 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
434 return DEAD_OBJECT;
435 }
436 return -error;
437 }
438
439 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000440 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
441 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
442 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700443 return DEAD_OBJECT;
444 }
445
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000446 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
447 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700448 return OK;
449}
450
451status_t InputChannel::receiveMessage(InputMessage* msg) {
452 ssize_t nRead;
453 do {
Chris Ye0783e992020-06-02 21:34:49 -0700454 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700455 } while (nRead == -1 && errno == EINTR);
456
457 if (nRead < 0) {
458 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000459 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
460 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700461 if (error == EAGAIN || error == EWOULDBLOCK) {
462 return WOULD_BLOCK;
463 }
464 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
465 return DEAD_OBJECT;
466 }
467 return -error;
468 }
469
470 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000471 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
472 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700473 return DEAD_OBJECT;
474 }
475
476 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000477 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700478 return BAD_VALUE;
479 }
480
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000481 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
482 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700483 return OK;
484}
485
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500486std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700487 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700488 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700489}
490
Garfield Tan15601662020-09-22 15:32:38 -0700491void InputChannel::copyTo(InputChannel& outChannel) const {
492 outChannel.mName = getName();
493 outChannel.mFd = dupFd();
494 outChannel.mToken = getConnectionToken();
495}
496
Chris Ye0783e992020-06-02 21:34:49 -0700497status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500498 if (parcel == nullptr) {
499 ALOGE("%s: Null parcel", __func__);
500 return BAD_VALUE;
501 }
502 return parcel->writeStrongBinder(mToken)
503 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700504}
505
Chris Ye0783e992020-06-02 21:34:49 -0700506status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500507 if (parcel == nullptr) {
508 ALOGE("%s: Null parcel", __func__);
509 return BAD_VALUE;
510 }
511 mToken = parcel->readStrongBinder();
512 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700513}
514
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700515sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500516 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700517}
518
Garfield Tan15601662020-09-22 15:32:38 -0700519base::unique_fd InputChannel::dupFd() const {
520 android::base::unique_fd newFd(::dup(getFd()));
521 if (!newFd.ok()) {
522 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
523 strerror(errno));
524 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
525 // If this process is out of file descriptors, then throwing that might end up exploding
526 // on the other side of a binder call, which isn't really helpful.
527 // Better to just crash here and hope that the FD leak is slow.
528 // Other failures could be client errors, so we still propagate those back to the caller.
529 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
530 getName().c_str());
531 return {};
532 }
533 return newFd;
534}
535
Jeff Brown5912f952013-07-01 19:10:31 -0700536// --- InputPublisher ---
537
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800538InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
539 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700540
541InputPublisher::~InputPublisher() {
542}
543
Garfield Tan1c7bc862020-01-28 13:24:04 -0800544status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
545 int32_t source, int32_t displayId,
546 std::array<uint8_t, 32> hmac, int32_t action,
547 int32_t flags, int32_t keyCode, int32_t scanCode,
548 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
549 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000550 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000551 std::string message =
552 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
553 mChannel->getName().c_str(), KeyEvent::actionToString(action),
554 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000555 ATRACE_NAME(message.c_str());
556 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000557 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000558 "channel '%s' publisher ~ %s: seq=%u, deviceId=%d, source=%s, "
559 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
560 "downTime=%" PRId64 ", eventTime=%" PRId64,
561 mChannel->getName().c_str(), __func__, seq, deviceId,
562 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
563 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700564
565 if (!seq) {
566 ALOGE("Attempted to publish a key event with sequence number 0.");
567 return BAD_VALUE;
568 }
569
570 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700571 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500572 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800573 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700574 msg.body.key.deviceId = deviceId;
575 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100576 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700577 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700578 msg.body.key.action = action;
579 msg.body.key.flags = flags;
580 msg.body.key.keyCode = keyCode;
581 msg.body.key.scanCode = scanCode;
582 msg.body.key.metaState = metaState;
583 msg.body.key.repeatCount = repeatCount;
584 msg.body.key.downTime = downTime;
585 msg.body.key.eventTime = eventTime;
586 return mChannel->sendMessage(&msg);
587}
588
589status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800590 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600591 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
592 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700593 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700594 float yPrecision, float xCursorPosition, float yCursorPosition,
595 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700596 uint32_t pointerCount, const PointerProperties* pointerProperties,
597 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000598 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000599 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
600 mChannel->getName().c_str(),
601 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000602 ATRACE_NAME(message.c_str());
603 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800604 if (verifyEvents()) {
605 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
606 pointerCoords, flags);
607 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000608 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700609 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700610 transform.dump(transformString, "transform", " ");
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000611 ALOGD("channel '%s' publisher ~ %s: seq=%u, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800612 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000613 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700614 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800615 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700616 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000617 mChannel->getName().c_str(), __func__, seq, deviceId,
618 inputEventSourceToString(source).c_str(), displayId,
619 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
620 metaState, buttonState, motionClassificationToString(classification), xPrecision,
621 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800622 }
Jeff Brown5912f952013-07-01 19:10:31 -0700623
624 if (!seq) {
625 ALOGE("Attempted to publish a motion event with sequence number 0.");
626 return BAD_VALUE;
627 }
628
629 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700630 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800631 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700632 return BAD_VALUE;
633 }
634
635 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700636 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500637 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800638 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700639 msg.body.motion.deviceId = deviceId;
640 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700641 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700642 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700643 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100644 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700645 msg.body.motion.flags = flags;
646 msg.body.motion.edgeFlags = edgeFlags;
647 msg.body.motion.metaState = metaState;
648 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800649 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700650 msg.body.motion.dsdx = transform.dsdx();
651 msg.body.motion.dtdx = transform.dtdx();
652 msg.body.motion.dtdy = transform.dtdy();
653 msg.body.motion.dsdy = transform.dsdy();
654 msg.body.motion.tx = transform.tx();
655 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700656 msg.body.motion.xPrecision = xPrecision;
657 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 msg.body.motion.xCursorPosition = xCursorPosition;
659 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700660 msg.body.motion.dsdxRaw = rawTransform.dsdx();
661 msg.body.motion.dtdxRaw = rawTransform.dtdx();
662 msg.body.motion.dtdyRaw = rawTransform.dtdy();
663 msg.body.motion.dsdyRaw = rawTransform.dsdy();
664 msg.body.motion.txRaw = rawTransform.tx();
665 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700666 msg.body.motion.downTime = downTime;
667 msg.body.motion.eventTime = eventTime;
668 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100669 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700670 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
671 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
672 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700673
Jeff Brown5912f952013-07-01 19:10:31 -0700674 return mChannel->sendMessage(&msg);
675}
676
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700677status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800678 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700679 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
680 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800681 ATRACE_NAME(message.c_str());
682 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000683 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, hasFocus=%s",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000684 mChannel->getName().c_str(), __func__, seq, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800685
686 InputMessage msg;
687 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500688 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800689 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000690 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800691 return mChannel->sendMessage(&msg);
692}
693
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800694status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
695 bool pointerCaptureEnabled) {
696 if (ATRACE_ENABLED()) {
697 std::string message =
698 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
699 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
700 ATRACE_NAME(message.c_str());
701 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000702 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000703 "channel '%s' publisher ~ %s: seq=%u, pointerCaptureEnabled=%s",
704 mChannel->getName().c_str(), __func__, seq, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800705
706 InputMessage msg;
707 msg.header.type = InputMessage::Type::CAPTURE;
708 msg.header.seq = seq;
709 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000710 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800711 return mChannel->sendMessage(&msg);
712}
713
arthurhung7632c332020-12-30 16:58:01 +0800714status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
715 bool isExiting) {
716 if (ATRACE_ENABLED()) {
717 std::string message =
718 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
719 mChannel->getName().c_str(), x, y, toString(isExiting));
720 ATRACE_NAME(message.c_str());
721 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000722 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000723 "channel '%s' publisher ~ %s: seq=%u, x=%f, y=%f, isExiting=%s",
724 mChannel->getName().c_str(), __func__, seq, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800725
726 InputMessage msg;
727 msg.header.type = InputMessage::Type::DRAG;
728 msg.header.seq = seq;
729 msg.body.drag.eventId = eventId;
730 msg.body.drag.isExiting = isExiting;
731 msg.body.drag.x = x;
732 msg.body.drag.y = y;
733 return mChannel->sendMessage(&msg);
734}
735
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700736status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
737 if (ATRACE_ENABLED()) {
738 std::string message =
739 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
740 mChannel->getName().c_str(), toString(isInTouchMode));
741 ATRACE_NAME(message.c_str());
742 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000743 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, isInTouchMode=%s",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000744 mChannel->getName().c_str(), __func__, seq, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700745
746 InputMessage msg;
747 msg.header.type = InputMessage::Type::TOUCH_MODE;
748 msg.header.seq = seq;
749 msg.body.touchMode.eventId = eventId;
750 msg.body.touchMode.isInTouchMode = isInTouchMode;
751 return mChannel->sendMessage(&msg);
752}
753
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000754android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000755 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s", mChannel->getName().c_str(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000756 __func__);
Jeff Brown5912f952013-07-01 19:10:31 -0700757
758 InputMessage msg;
759 status_t result = mChannel->receiveMessage(&msg);
760 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000761 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700762 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000763 if (msg.header.type == InputMessage::Type::FINISHED) {
764 return Finished{
765 .seq = msg.header.seq,
766 .handled = msg.body.finished.handled,
767 .consumeTime = msg.body.finished.consumeTime,
768 };
Jeff Brown5912f952013-07-01 19:10:31 -0700769 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000770
771 if (msg.header.type == InputMessage::Type::TIMELINE) {
772 return Timeline{
773 .inputEventId = msg.body.timeline.eventId,
774 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
775 };
776 }
777
778 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800779 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000780 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700781}
782
783// --- InputConsumer ---
784
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500785InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800786 : InputConsumer(channel, isTouchResamplingEnabled()) {}
787
788InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
789 bool enableTouchResampling)
790 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700791
792InputConsumer::~InputConsumer() {
793}
794
795bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600796 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700797}
798
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800799status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
800 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000801 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
802 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
803 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700804
805 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700806 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700807
808 // Fetch the next input message.
809 // Loop until an event can be returned or no additional events are received.
810 while (!*outEvent) {
811 if (mMsgDeferred) {
812 // mMsg contains a valid input message from the previous call to consume
813 // that has not yet been processed.
814 mMsgDeferred = false;
815 } else {
816 // Receive a fresh message.
817 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000818 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800819 const auto [_, inserted] =
820 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
821 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
822 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000823 }
Jeff Brown5912f952013-07-01 19:10:31 -0700824 if (result) {
825 // Consume the next batched event unless batches are being held for later.
826 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800827 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700828 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000829 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
830 "channel '%s' consumer ~ consumed batch event, seq=%u",
831 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700832 break;
833 }
834 }
835 return result;
836 }
837 }
838
839 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700840 case InputMessage::Type::KEY: {
841 KeyEvent* keyEvent = factory->createKeyEvent();
842 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700843
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700844 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500845 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700846 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000847 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
848 "channel '%s' consumer ~ consumed key event, seq=%u",
849 mChannel->getName().c_str(), *outSeq);
850 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700851 }
Jeff Brown5912f952013-07-01 19:10:31 -0700852
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700853 case InputMessage::Type::MOTION: {
854 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
855 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500856 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700857 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500858 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000859 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
860 "channel '%s' consumer ~ appended to batch event",
861 mChannel->getName().c_str());
862 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700863 } else if (isPointerEvent(mMsg.body.motion.source) &&
864 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
865 // No need to process events that we are going to cancel anyways
866 const size_t count = batch.samples.size();
867 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500868 const InputMessage& msg = batch.samples[i];
869 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700870 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500871 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
872 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700873 } else {
874 // We cannot append to the batch in progress, so we need to consume
875 // the previous batch right now and defer the new message until later.
876 mMsgDeferred = true;
877 status_t result = consumeSamples(factory, batch, batch.samples.size(),
878 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500879 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700880 if (result) {
881 return result;
882 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000883 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
884 "channel '%s' consumer ~ consumed batch event and "
885 "deferred current event, seq=%u",
886 mChannel->getName().c_str(), *outSeq);
887 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700888 }
Jeff Brown5912f952013-07-01 19:10:31 -0700889 }
Jeff Brown5912f952013-07-01 19:10:31 -0700890
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800891 // Start a new batch if needed.
892 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
893 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500894 Batch batch;
895 batch.samples.push_back(mMsg);
896 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000897 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
898 "channel '%s' consumer ~ started batch event",
899 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800900 break;
901 }
Jeff Brown5912f952013-07-01 19:10:31 -0700902
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800903 MotionEvent* motionEvent = factory->createMotionEvent();
904 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700905
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800906 updateTouchState(mMsg);
907 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500908 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800909 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800910
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000911 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
912 "channel '%s' consumer ~ consumed motion event, seq=%u",
913 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800914 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700915 }
Jeff Brown5912f952013-07-01 19:10:31 -0700916
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000917 case InputMessage::Type::FINISHED:
918 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000919 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
920 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800921 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800922 break;
923 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800924
925 case InputMessage::Type::FOCUS: {
926 FocusEvent* focusEvent = factory->createFocusEvent();
927 if (!focusEvent) return NO_MEMORY;
928
929 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500930 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800931 *outEvent = focusEvent;
932 break;
933 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800934
935 case InputMessage::Type::CAPTURE: {
936 CaptureEvent* captureEvent = factory->createCaptureEvent();
937 if (!captureEvent) return NO_MEMORY;
938
939 initializeCaptureEvent(captureEvent, &mMsg);
940 *outSeq = mMsg.header.seq;
941 *outEvent = captureEvent;
942 break;
943 }
arthurhung7632c332020-12-30 16:58:01 +0800944
945 case InputMessage::Type::DRAG: {
946 DragEvent* dragEvent = factory->createDragEvent();
947 if (!dragEvent) return NO_MEMORY;
948
949 initializeDragEvent(dragEvent, &mMsg);
950 *outSeq = mMsg.header.seq;
951 *outEvent = dragEvent;
952 break;
953 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700954
955 case InputMessage::Type::TOUCH_MODE: {
956 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
957 if (!touchModeEvent) return NO_MEMORY;
958
959 initializeTouchModeEvent(touchModeEvent, &mMsg);
960 *outSeq = mMsg.header.seq;
961 *outEvent = touchModeEvent;
962 break;
963 }
Jeff Brown5912f952013-07-01 19:10:31 -0700964 }
965 }
966 return OK;
967}
968
969status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800970 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700971 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700972 for (size_t i = mBatches.size(); i > 0; ) {
973 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500974 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700975 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800976 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500977 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700978 return result;
979 }
980
Michael Wright32232172013-10-21 12:05:22 -0700981 nsecs_t sampleTime = frameTime;
982 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800983 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -0700984 }
Jeff Brown5912f952013-07-01 19:10:31 -0700985 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
986 if (split < 0) {
987 continue;
988 }
989
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800990 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700991 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500992 if (batch.samples.empty()) {
993 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700994 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700995 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500996 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700997 }
Michael Wright32232172013-10-21 12:05:22 -0700998 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700999 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1000 }
1001 return result;
1002 }
1003
1004 return WOULD_BLOCK;
1005}
1006
1007status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001008 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001009 MotionEvent* motionEvent = factory->createMotionEvent();
1010 if (! motionEvent) return NO_MEMORY;
1011
1012 uint32_t chain = 0;
1013 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001014 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001015 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001016 if (i) {
1017 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001018 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001019 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001020 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001021 addSample(motionEvent, &msg);
1022 } else {
1023 initializeMotionEvent(motionEvent, &msg);
1024 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001025 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001026 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001027 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001028
1029 *outSeq = chain;
1030 *outEvent = motionEvent;
1031 return OK;
1032}
1033
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001034void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001035 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001036 return;
1037 }
1038
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001039 int32_t deviceId = msg.body.motion.deviceId;
1040 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001041
1042 // Update the touch state history to incorporate the new input message.
1043 // If the message is in the past relative to the most recently produced resampled
1044 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001045 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001046 case AMOTION_EVENT_ACTION_DOWN: {
1047 ssize_t index = findTouchState(deviceId, source);
1048 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001049 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001050 index = mTouchStates.size() - 1;
1051 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001052 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001053 touchState.initialize(deviceId, source);
1054 touchState.addHistory(msg);
1055 break;
1056 }
1057
1058 case AMOTION_EVENT_ACTION_MOVE: {
1059 ssize_t index = findTouchState(deviceId, source);
1060 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001061 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001062 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001063 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001064 }
1065 break;
1066 }
1067
1068 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1069 ssize_t index = findTouchState(deviceId, source);
1070 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001071 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001072 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001073 rewriteMessage(touchState, msg);
1074 }
1075 break;
1076 }
1077
1078 case AMOTION_EVENT_ACTION_POINTER_UP: {
1079 ssize_t index = findTouchState(deviceId, source);
1080 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001081 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001082 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001083 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001084 }
1085 break;
1086 }
1087
1088 case AMOTION_EVENT_ACTION_SCROLL: {
1089 ssize_t index = findTouchState(deviceId, source);
1090 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001091 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001092 rewriteMessage(touchState, msg);
1093 }
1094 break;
1095 }
1096
1097 case AMOTION_EVENT_ACTION_UP:
1098 case AMOTION_EVENT_ACTION_CANCEL: {
1099 ssize_t index = findTouchState(deviceId, source);
1100 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001101 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001102 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001103 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001104 }
1105 break;
1106 }
1107 }
1108}
1109
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001110/**
1111 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1112 *
1113 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1114 * is in the past relative to msg and the past two events do not contain identical coordinates),
1115 * then invalidate the lastResample data for that pointer.
1116 * If the two past events have identical coordinates, then lastResample data for that pointer will
1117 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1118 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1119 * not equal to x0 is received.
1120 */
1121void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001122 nsecs_t eventTime = msg.body.motion.eventTime;
1123 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1124 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001125 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001126 if (eventTime < state.lastResample.eventTime ||
1127 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001128 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1129 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001130 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1131 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1132 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001133 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1134 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001135 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001136 } else {
1137 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001138 }
Jeff Brown5912f952013-07-01 19:10:31 -07001139 }
1140 }
1141}
1142
1143void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1144 const InputMessage* next) {
1145 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001146 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001147 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1148 return;
1149 }
1150
1151 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1152 if (index < 0) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001153 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001154 return;
1155 }
1156
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001157 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001158 if (touchState.historySize < 1) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001159 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001160 return;
1161 }
1162
1163 // Ensure that the current sample has all of the pointers that need to be reported.
1164 const History* current = touchState.getHistory(0);
1165 size_t pointerCount = event->getPointerCount();
1166 for (size_t i = 0; i < pointerCount; i++) {
1167 uint32_t id = event->getPointerId(i);
1168 if (!current->idBits.hasBit(id)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001169 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001170 return;
1171 }
1172 }
1173
1174 // Find the data to use for resampling.
1175 const History* other;
1176 History future;
1177 float alpha;
1178 if (next) {
1179 // Interpolate between current sample and future sample.
1180 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001181 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001182 other = &future;
1183 nsecs_t delta = future.eventTime - current->eventTime;
1184 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001185 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1186 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001187 return;
1188 }
1189 alpha = float(sampleTime - current->eventTime) / delta;
1190 } else if (touchState.historySize >= 2) {
1191 // Extrapolate future sample using current sample and past sample.
1192 // So other->eventTime <= current->eventTime <= sampleTime.
1193 other = touchState.getHistory(1);
1194 nsecs_t delta = current->eventTime - other->eventTime;
1195 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001196 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1197 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001198 return;
1199 } else if (delta > RESAMPLE_MAX_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001200 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1201 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001202 return;
1203 }
1204 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1205 if (sampleTime > maxPredict) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001206 ALOGD_IF(DEBUG_RESAMPLING,
1207 "Sample time is too far in the future, adjusting prediction "
1208 "from %" PRId64 " to %" PRId64 " ns.",
1209 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001210 sampleTime = maxPredict;
1211 }
1212 alpha = float(current->eventTime - sampleTime) / delta;
1213 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001214 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001215 return;
1216 }
1217
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001218 if (current->eventTime == sampleTime) {
1219 // Prevents having 2 events with identical times and coordinates.
1220 return;
1221 }
1222
Jeff Brown5912f952013-07-01 19:10:31 -07001223 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001224 History oldLastResample;
1225 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001226 touchState.lastResample.eventTime = sampleTime;
1227 touchState.lastResample.idBits.clear();
1228 for (size_t i = 0; i < pointerCount; i++) {
1229 uint32_t id = event->getPointerId(i);
1230 touchState.lastResample.idToIndex[id] = i;
1231 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001232 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1233 // We maintain the previously resampled value for this pointer (stored in
1234 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1235 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001236 // The isResampled flag isn't cleared as the values don't reflect what the device is
1237 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001238
1239 // We know here that the coordinates for the pointer haven't changed because we
1240 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1241 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1242 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1243 continue;
1244 }
1245
Jeff Brown5912f952013-07-01 19:10:31 -07001246 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1247 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001248 resampledCoords.copyFrom(currentCoords);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001249 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001250 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001251 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001252 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001253 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001254 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001255 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001256 ALOGD_IF(DEBUG_RESAMPLING,
1257 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1258 "other (%0.3f, %0.3f), alpha %0.3f",
1259 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1260 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001261 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001262 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1263 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1264 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001265 }
1266 }
1267
1268 event->addSample(sampleTime, touchState.lastResample.pointers);
1269}
1270
1271bool InputConsumer::shouldResampleTool(int32_t toolType) {
1272 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1273 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1274}
1275
1276status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001277 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1278 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1279 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001280
1281 if (!seq) {
1282 ALOGE("Attempted to send a finished signal with sequence number 0.");
1283 return BAD_VALUE;
1284 }
1285
1286 // Send finished signals for the batch sequence chain first.
1287 size_t seqChainCount = mSeqChains.size();
1288 if (seqChainCount) {
1289 uint32_t currentSeq = seq;
1290 uint32_t chainSeqs[seqChainCount];
1291 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001292 for (size_t i = seqChainCount; i > 0; ) {
1293 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001294 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001295 if (seqChain.seq == currentSeq) {
1296 currentSeq = seqChain.chain;
1297 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001298 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001299 }
1300 }
1301 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001302 while (!status && chainIndex > 0) {
1303 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001304 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1305 }
1306 if (status) {
1307 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001308 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001309 SeqChain seqChain;
1310 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1311 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001312 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001313 if (!chainIndex) break;
1314 chainIndex--;
1315 }
Jeff Brown5912f952013-07-01 19:10:31 -07001316 return status;
1317 }
1318 }
1319
1320 // Send finished signal for the last message in the batch.
1321 return sendUnchainedFinishedSignal(seq, handled);
1322}
1323
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001324status_t InputConsumer::sendTimeline(int32_t inputEventId,
1325 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001326 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1327 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1328 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1329 mChannel->getName().c_str(), inputEventId,
1330 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1331 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001332
1333 InputMessage msg;
1334 msg.header.type = InputMessage::Type::TIMELINE;
1335 msg.header.seq = 0;
1336 msg.body.timeline.eventId = inputEventId;
1337 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1338 return mChannel->sendMessage(&msg);
1339}
1340
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001341nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1342 auto it = mConsumeTimes.find(seq);
1343 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1344 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1345 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1346 seq);
1347 return it->second;
1348}
1349
1350void InputConsumer::popConsumeTime(uint32_t seq) {
1351 mConsumeTimes.erase(seq);
1352}
1353
Jeff Brown5912f952013-07-01 19:10:31 -07001354status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1355 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001356 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001357 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001358 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001359 msg.body.finished.consumeTime = getConsumeTime(seq);
1360 status_t result = mChannel->sendMessage(&msg);
1361 if (result == OK) {
1362 // Remove the consume time if the socket write succeeded. We will not need to ack this
1363 // message anymore. If the socket write did not succeed, we will try again and will still
1364 // need consume time.
1365 popConsumeTime(seq);
1366 }
1367 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001368}
1369
Jeff Brown5912f952013-07-01 19:10:31 -07001370bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001371 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001372}
1373
Arthur Hungc7812be2020-02-27 22:40:27 +08001374int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001375 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001376 return AINPUT_SOURCE_CLASS_NONE;
1377 }
1378
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001379 const Batch& batch = mBatches[0];
1380 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001381 return head.body.motion.source;
1382}
1383
Jeff Brown5912f952013-07-01 19:10:31 -07001384ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1385 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001386 const Batch& batch = mBatches[i];
1387 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001388 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1389 return i;
1390 }
1391 }
1392 return -1;
1393}
1394
1395ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1396 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001397 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001398 if (touchState.deviceId == deviceId && touchState.source == source) {
1399 return i;
1400 }
1401 }
1402 return -1;
1403}
1404
1405void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001406 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001407 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1408 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1409 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1410 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001411}
1412
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001413void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001414 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001415}
1416
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001417void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001418 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001419}
1420
arthurhung7632c332020-12-30 16:58:01 +08001421void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1422 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1423 msg->body.drag.isExiting);
1424}
1425
Jeff Brown5912f952013-07-01 19:10:31 -07001426void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001427 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001428 PointerProperties pointerProperties[pointerCount];
1429 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001430 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001431 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1432 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1433 }
1434
chaviw9eaa22c2020-07-01 16:21:27 -07001435 ui::Transform transform;
1436 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1437 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001438 ui::Transform displayTransform;
1439 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1440 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1441 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001442 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1443 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1444 msg->body.motion.actionButton, msg->body.motion.flags,
1445 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001446 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1447 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1448 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001449 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1450 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001451}
1452
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001453void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1454 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1455}
1456
Jeff Brown5912f952013-07-01 19:10:31 -07001457void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001458 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001459 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001460 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001461 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1462 }
1463
1464 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1465 event->addSample(msg->body.motion.eventTime, pointerCoords);
1466}
1467
1468bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001469 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001470 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001471 if (head.body.motion.pointerCount != pointerCount
1472 || head.body.motion.action != msg->body.motion.action) {
1473 return false;
1474 }
1475 for (size_t i = 0; i < pointerCount; i++) {
1476 if (head.body.motion.pointers[i].properties
1477 != msg->body.motion.pointers[i].properties) {
1478 return false;
1479 }
1480 }
1481 return true;
1482}
1483
1484ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1485 size_t numSamples = batch.samples.size();
1486 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001487 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001488 index += 1;
1489 }
1490 return ssize_t(index) - 1;
1491}
1492
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001493std::string InputConsumer::dump() const {
1494 std::string out;
1495 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1496 out = out + "mChannel = " + mChannel->getName() + "\n";
1497 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1498 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001499 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001500 }
1501 out += "Batches:\n";
1502 for (const Batch& batch : mBatches) {
1503 out += " Batch:\n";
1504 for (const InputMessage& msg : batch.samples) {
1505 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001506 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001507 switch (msg.header.type) {
1508 case InputMessage::Type::KEY: {
1509 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1510 KeyEvent::actionToString(
1511 msg.body.key.action),
1512 msg.body.key.keyCode);
1513 break;
1514 }
1515 case InputMessage::Type::MOTION: {
1516 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1517 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1518 const float x = msg.body.motion.pointers[i].coords.getX();
1519 const float y = msg.body.motion.pointers[i].coords.getY();
1520 out += android::base::StringPrintf("\n Pointer %" PRIu32
1521 " : x=%.1f y=%.1f",
1522 i, x, y);
1523 }
1524 break;
1525 }
1526 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001527 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1528 toString(msg.body.finished.handled),
1529 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001530 break;
1531 }
1532 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001533 out += android::base::StringPrintf("hasFocus=%s",
1534 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001535 break;
1536 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001537 case InputMessage::Type::CAPTURE: {
1538 out += android::base::StringPrintf("hasCapture=%s",
1539 toString(msg.body.capture
1540 .pointerCaptureEnabled));
1541 break;
1542 }
arthurhung7632c332020-12-30 16:58:01 +08001543 case InputMessage::Type::DRAG: {
1544 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1545 msg.body.drag.x, msg.body.drag.y,
1546 toString(msg.body.drag.isExiting));
1547 break;
1548 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001549 case InputMessage::Type::TIMELINE: {
1550 const nsecs_t gpuCompletedTime =
1551 msg.body.timeline
1552 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1553 const nsecs_t presentTime =
1554 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1555 out += android::base::StringPrintf("inputEventId=%" PRId32
1556 ", gpuCompletedTime=%" PRId64
1557 ", presentTime=%" PRId64,
1558 msg.body.timeline.eventId, gpuCompletedTime,
1559 presentTime);
1560 break;
1561 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001562 case InputMessage::Type::TOUCH_MODE: {
1563 out += android::base::StringPrintf("isInTouchMode=%s",
1564 toString(msg.body.touchMode.isInTouchMode));
1565 break;
1566 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001567 }
1568 out += "\n";
1569 }
1570 }
1571 if (mBatches.empty()) {
1572 out += " <empty>\n";
1573 }
1574 out += "mSeqChains:\n";
1575 for (const SeqChain& chain : mSeqChains) {
1576 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1577 chain.chain);
1578 }
1579 if (mSeqChains.empty()) {
1580 out += " <empty>\n";
1581 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001582 out += "mConsumeTimes:\n";
1583 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1584 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1585 consumeTime);
1586 }
1587 if (mConsumeTimes.empty()) {
1588 out += " <empty>\n";
1589 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001590 return out;
1591}
1592
Jeff Brown5912f952013-07-01 19:10:31 -07001593} // namespace android