blob: bbbebf7dcde73dacb0b44dcf523e6a1a64458d7c [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"
Zimd8402b62023-06-02 11:56:26 +01007#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown5912f952013-07-01 19:10:31 -07008
Jeff Brown5912f952013-07-01 19:10:31 -07009#include <errno.h>
10#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070011#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070012#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070013#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070014#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070015#include <unistd.h>
16
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070017#include <android-base/logging.h>
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000018#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000019#include <android-base/stringprintf.h>
20#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080022#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070023#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000024#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070025
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <input/InputTransport.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000027#include <input/TraceTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000029namespace {
30
31/**
32 * Log debug messages about channel messages (send message, receive message).
33 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
34 * (requires restart)
35 */
36const bool DEBUG_CHANNEL_MESSAGES =
37 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
38
39/**
40 * Log debug messages whenever InputChannel objects are created/destroyed.
41 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
42 * (requires restart)
43 */
44const bool DEBUG_CHANNEL_LIFECYCLE =
45 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
46
47/**
48 * Log debug messages relating to the consumer end of the transport channel.
49 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
50 */
51
52const bool DEBUG_TRANSPORT_CONSUMER =
53 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
54
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000055const bool IS_DEBUGGABLE_BUILD =
56#if defined(__ANDROID__)
57 android::base::GetBoolProperty("ro.debuggable", false);
58#else
59 true;
60#endif
61
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000062/**
63 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000064 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
65 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
66 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000067 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000068bool debugTransportPublisher() {
69 if (!IS_DEBUGGABLE_BUILD) {
70 static const bool DEBUG_TRANSPORT_PUBLISHER =
71 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
72 return DEBUG_TRANSPORT_PUBLISHER;
73 }
74 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
75}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000076
77/**
78 * Log debug messages about touch event resampling.
Harry Cutts6c658cc2023-08-02 14:40:40 +000079 *
80 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG".
81 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
82 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000083 */
Harry Cutts6c658cc2023-08-02 14:40:40 +000084bool debugResampling() {
85 if (!IS_DEBUGGABLE_BUILD) {
86 static const bool DEBUG_TRANSPORT_RESAMPLING =
87 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
88 ANDROID_LOG_INFO);
89 return DEBUG_TRANSPORT_RESAMPLING;
90 }
91 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
92}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000093
94} // namespace
95
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070096using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +000097using android::base::StringPrintf;
98
Jeff Brown5912f952013-07-01 19:10:31 -070099namespace android {
100
101// Socket buffer size. The default is typically about 128KB, which is much larger than
102// we really need. So we make it smaller. It just needs to be big enough to hold
103// a few dozen large multi-finger motion events in the case where an application gets
104// behind processing touches.
105static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
106
107// Nanoseconds per milliseconds.
108static const nsecs_t NANOS_PER_MS = 1000000;
109
110// Latency added during resampling. A few milliseconds doesn't hurt much but
111// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800112const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700113
114// Minimum time difference between consecutive samples before attempting to resample.
115static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
116
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700117// Maximum time difference between consecutive samples before attempting to resample
118// by extrapolation.
119static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
120
Jeff Brown5912f952013-07-01 19:10:31 -0700121// Maximum time to predict forward from the last known state, to avoid predicting too
122// far into the future. This time is further bounded by 50% of the last time delta.
123static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
124
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600125/**
126 * System property for enabling / disabling touch resampling.
127 * Resampling extrapolates / interpolates the reported touch event coordinates to better
128 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
129 * Resampling is not needed (and should be disabled) on hardware that already
130 * has touch events triggered by VSYNC.
131 * Set to "1" to enable resampling (default).
132 * Set to "0" to disable resampling.
133 * Resampling is enabled by default.
134 */
135static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
136
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800137/**
138 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
139 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
140 */
141static bool verifyEvents() {
142 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
143}
144
Jeff Brown5912f952013-07-01 19:10:31 -0700145template<typename T>
146inline static T min(const T& a, const T& b) {
147 return a < b ? a : b;
148}
149
150inline static float lerp(float a, float b, float alpha) {
151 return a + alpha * (b - a);
152}
153
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800154inline static bool isPointerEvent(int32_t source) {
155 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
156}
157
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800158inline static const char* toString(bool value) {
159 return value ? "true" : "false";
160}
161
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700162static bool shouldResampleTool(ToolType toolType) {
163 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
164}
165
Jeff Brown5912f952013-07-01 19:10:31 -0700166// --- InputMessage ---
167
168bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000169 if (size() != actualSize) {
170 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
171 return false;
172 }
173
174 switch (header.type) {
175 case Type::KEY:
176 return true;
177 case Type::MOTION: {
178 const bool valid =
179 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
180 if (!valid) {
181 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
182 }
183 return valid;
184 }
185 case Type::FINISHED:
186 case Type::FOCUS:
187 case Type::CAPTURE:
188 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700189 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000190 return true;
191 case Type::TIMELINE: {
192 const nsecs_t gpuCompletedTime =
193 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
194 const nsecs_t presentTime =
195 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
196 const bool valid = presentTime > gpuCompletedTime;
197 if (!valid) {
198 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
199 " presentTime = %" PRId64,
200 gpuCompletedTime, presentTime);
201 }
202 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700203 }
204 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000205 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700206 return false;
207}
208
209size_t InputMessage::size() const {
210 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700211 case Type::KEY:
212 return sizeof(Header) + body.key.size();
213 case Type::MOTION:
214 return sizeof(Header) + body.motion.size();
215 case Type::FINISHED:
216 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800217 case Type::FOCUS:
218 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800219 case Type::CAPTURE:
220 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800221 case Type::DRAG:
222 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000223 case Type::TIMELINE:
224 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700225 case Type::TOUCH_MODE:
226 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700227 }
228 return sizeof(Header);
229}
230
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800231/**
232 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
233 * memory to zero, then only copy the valid bytes on a per-field basis.
234 */
235void InputMessage::getSanitizedCopy(InputMessage* msg) const {
236 memset(msg, 0, sizeof(*msg));
237
238 // Write the header
239 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500240 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800241
242 // Write the body
243 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700244 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800245 // int32_t eventId
246 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800247 // nsecs_t eventTime
248 msg->body.key.eventTime = body.key.eventTime;
249 // int32_t deviceId
250 msg->body.key.deviceId = body.key.deviceId;
251 // int32_t source
252 msg->body.key.source = body.key.source;
253 // int32_t displayId
254 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600255 // std::array<uint8_t, 32> hmac
256 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800257 // int32_t action
258 msg->body.key.action = body.key.action;
259 // int32_t flags
260 msg->body.key.flags = body.key.flags;
261 // int32_t keyCode
262 msg->body.key.keyCode = body.key.keyCode;
263 // int32_t scanCode
264 msg->body.key.scanCode = body.key.scanCode;
265 // int32_t metaState
266 msg->body.key.metaState = body.key.metaState;
267 // int32_t repeatCount
268 msg->body.key.repeatCount = body.key.repeatCount;
269 // nsecs_t downTime
270 msg->body.key.downTime = body.key.downTime;
271 break;
272 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700273 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800274 // int32_t eventId
275 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700276 // uint32_t pointerCount
277 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800278 // nsecs_t eventTime
279 msg->body.motion.eventTime = body.motion.eventTime;
280 // int32_t deviceId
281 msg->body.motion.deviceId = body.motion.deviceId;
282 // int32_t source
283 msg->body.motion.source = body.motion.source;
284 // int32_t displayId
285 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600286 // std::array<uint8_t, 32> hmac
287 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800288 // int32_t action
289 msg->body.motion.action = body.motion.action;
290 // int32_t actionButton
291 msg->body.motion.actionButton = body.motion.actionButton;
292 // int32_t flags
293 msg->body.motion.flags = body.motion.flags;
294 // int32_t metaState
295 msg->body.motion.metaState = body.motion.metaState;
296 // int32_t buttonState
297 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800298 // MotionClassification classification
299 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800300 // int32_t edgeFlags
301 msg->body.motion.edgeFlags = body.motion.edgeFlags;
302 // nsecs_t downTime
303 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700304
305 msg->body.motion.dsdx = body.motion.dsdx;
306 msg->body.motion.dtdx = body.motion.dtdx;
307 msg->body.motion.dtdy = body.motion.dtdy;
308 msg->body.motion.dsdy = body.motion.dsdy;
309 msg->body.motion.tx = body.motion.tx;
310 msg->body.motion.ty = body.motion.ty;
311
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800312 // float xPrecision
313 msg->body.motion.xPrecision = body.motion.xPrecision;
314 // float yPrecision
315 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700316 // float xCursorPosition
317 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
318 // float yCursorPosition
319 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700320
321 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
322 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
323 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
324 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
325 msg->body.motion.txRaw = body.motion.txRaw;
326 msg->body.motion.tyRaw = body.motion.tyRaw;
327
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800328 //struct Pointer pointers[MAX_POINTERS]
329 for (size_t i = 0; i < body.motion.pointerCount; i++) {
330 // PointerProperties properties
331 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
332 msg->body.motion.pointers[i].properties.toolType =
333 body.motion.pointers[i].properties.toolType,
334 // PointerCoords coords
335 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
336 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
337 memcpy(&msg->body.motion.pointers[i].coords.values[0],
338 &body.motion.pointers[i].coords.values[0],
339 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800340 msg->body.motion.pointers[i].coords.isResampled =
341 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800342 }
343 break;
344 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700345 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800346 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000347 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800348 break;
349 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800350 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800351 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800352 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800353 break;
354 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800355 case InputMessage::Type::CAPTURE: {
356 msg->body.capture.eventId = body.capture.eventId;
357 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
358 break;
359 }
arthurhung7632c332020-12-30 16:58:01 +0800360 case InputMessage::Type::DRAG: {
361 msg->body.drag.eventId = body.drag.eventId;
362 msg->body.drag.x = body.drag.x;
363 msg->body.drag.y = body.drag.y;
364 msg->body.drag.isExiting = body.drag.isExiting;
365 break;
366 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000367 case InputMessage::Type::TIMELINE: {
368 msg->body.timeline.eventId = body.timeline.eventId;
369 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
370 break;
371 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700372 case InputMessage::Type::TOUCH_MODE: {
373 msg->body.touchMode.eventId = body.touchMode.eventId;
374 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
375 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800376 }
377}
Jeff Brown5912f952013-07-01 19:10:31 -0700378
379// --- InputChannel ---
380
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500381std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700383 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
384 if (result != 0) {
385 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
386 strerror(errno));
387 return nullptr;
388 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500389 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500390 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700391}
392
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500393InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
394 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000395 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
396 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700397}
398
399InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000400 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
401 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700402}
403
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800404status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500405 std::unique_ptr<InputChannel>& outServerChannel,
406 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700407 int sockets[2];
408 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
409 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000410 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
411 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500412 outServerChannel.reset();
413 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700414 return result;
415 }
416
417 int bufferSize = SOCKET_BUFFER_SIZE;
418 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
419 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
420 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
421 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
422
Siarhei Vishniakou4c155eb2023-06-30 11:47:12 -0700423 sp<IBinder> token = sp<BBinder>::make();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700424
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700425 std::string serverChannelName = name + " (server)";
426 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700427 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700428
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700429 std::string clientChannelName = name + " (client)";
430 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700431 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700432 return OK;
433}
434
435status_t InputChannel::sendMessage(const InputMessage* msg) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000436 ATRACE_NAME_IF(ATRACE_ENABLED(),
437 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32
438 ")",
439 mName.c_str(), msg->header.seq, msg->header.type));
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800440 const size_t msgLength = msg->size();
441 InputMessage cleanMsg;
442 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700443 ssize_t nWrite;
444 do {
Chris Ye0783e992020-06-02 21:34:49 -0700445 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700446 } while (nWrite == -1 && errno == EINTR);
447
448 if (nWrite < 0) {
449 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000450 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
451 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700452 if (error == EAGAIN || error == EWOULDBLOCK) {
453 return WOULD_BLOCK;
454 }
455 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
456 return DEAD_OBJECT;
457 }
458 return -error;
459 }
460
461 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000462 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
463 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
464 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700465 return DEAD_OBJECT;
466 }
467
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000468 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
469 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100470
Jeff Brown5912f952013-07-01 19:10:31 -0700471 return OK;
472}
473
474status_t InputChannel::receiveMessage(InputMessage* msg) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000475 ATRACE_NAME_IF(ATRACE_ENABLED(),
476 StringPrintf("receiveMessage(inputChannel=%s)", mName.c_str()));
Jeff Brown5912f952013-07-01 19:10:31 -0700477 ssize_t nRead;
478 do {
Chris Ye0783e992020-06-02 21:34:49 -0700479 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700480 } while (nRead == -1 && errno == EINTR);
481
482 if (nRead < 0) {
483 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000484 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
485 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700486 if (error == EAGAIN || error == EWOULDBLOCK) {
487 return WOULD_BLOCK;
488 }
489 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
490 return DEAD_OBJECT;
491 }
492 return -error;
493 }
494
495 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000496 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
497 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700498 return DEAD_OBJECT;
499 }
500
501 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000502 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700503 return BAD_VALUE;
504 }
505
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000506 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
507 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100508 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000509 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100510 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
511 ", type=0x%" PRIx32 ")",
512 mName.c_str(), msg->header.seq, msg->header.type);
513 ATRACE_NAME(message.c_str());
514 }
Jeff Brown5912f952013-07-01 19:10:31 -0700515 return OK;
516}
517
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500518std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700519 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700520 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700521}
522
Garfield Tan15601662020-09-22 15:32:38 -0700523void InputChannel::copyTo(InputChannel& outChannel) const {
524 outChannel.mName = getName();
525 outChannel.mFd = dupFd();
526 outChannel.mToken = getConnectionToken();
527}
528
Chris Ye0783e992020-06-02 21:34:49 -0700529status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500530 if (parcel == nullptr) {
531 ALOGE("%s: Null parcel", __func__);
532 return BAD_VALUE;
533 }
534 return parcel->writeStrongBinder(mToken)
535 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700536}
537
Chris Ye0783e992020-06-02 21:34:49 -0700538status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500539 if (parcel == nullptr) {
540 ALOGE("%s: Null parcel", __func__);
541 return BAD_VALUE;
542 }
543 mToken = parcel->readStrongBinder();
544 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700545}
546
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700547sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500548 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700549}
550
Garfield Tan15601662020-09-22 15:32:38 -0700551base::unique_fd InputChannel::dupFd() const {
552 android::base::unique_fd newFd(::dup(getFd()));
553 if (!newFd.ok()) {
554 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
555 strerror(errno));
556 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
557 // If this process is out of file descriptors, then throwing that might end up exploding
558 // on the other side of a binder call, which isn't really helpful.
559 // Better to just crash here and hope that the FD leak is slow.
560 // Other failures could be client errors, so we still propagate those back to the caller.
561 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
562 getName().c_str());
563 return {};
564 }
565 return newFd;
566}
567
Jeff Brown5912f952013-07-01 19:10:31 -0700568// --- InputPublisher ---
569
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800570InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
571 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700572
573InputPublisher::~InputPublisher() {
574}
575
Garfield Tan1c7bc862020-01-28 13:24:04 -0800576status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
577 int32_t source, int32_t displayId,
578 std::array<uint8_t, 32> hmac, int32_t action,
579 int32_t flags, int32_t keyCode, int32_t scanCode,
580 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
581 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000582 ATRACE_NAME_IF(ATRACE_ENABLED(),
583 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
584 mChannel->getName().c_str(), KeyEvent::actionToString(action),
585 KeyEvent::getLabel(keyCode)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000586 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000587 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000588 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
589 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000590 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000591 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
592 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700593
594 if (!seq) {
595 ALOGE("Attempted to publish a key event with sequence number 0.");
596 return BAD_VALUE;
597 }
598
599 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700600 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500601 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800602 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700603 msg.body.key.deviceId = deviceId;
604 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100605 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700606 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700607 msg.body.key.action = action;
608 msg.body.key.flags = flags;
609 msg.body.key.keyCode = keyCode;
610 msg.body.key.scanCode = scanCode;
611 msg.body.key.metaState = metaState;
612 msg.body.key.repeatCount = repeatCount;
613 msg.body.key.downTime = downTime;
614 msg.body.key.eventTime = eventTime;
615 return mChannel->sendMessage(&msg);
616}
617
618status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800619 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600620 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
621 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700622 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700623 float yPrecision, float xCursorPosition, float yCursorPosition,
624 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700625 uint32_t pointerCount, const PointerProperties* pointerProperties,
626 const PointerCoords* pointerCoords) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000627 ATRACE_NAME_IF(ATRACE_ENABLED(),
628 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
629 mChannel->getName().c_str(),
630 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800631 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700632 Result<void> result =
633 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
634 pointerCoords, flags);
635 if (!result.ok()) {
636 LOG(FATAL) << "Bad stream: " << result.error();
637 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800638 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000639 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700640 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700641 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000642 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800643 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000644 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700645 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800646 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700647 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000648 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000649 inputEventSourceToString(source).c_str(), displayId,
650 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
651 metaState, buttonState, motionClassificationToString(classification), xPrecision,
652 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800653 }
Jeff Brown5912f952013-07-01 19:10:31 -0700654
655 if (!seq) {
656 ALOGE("Attempted to publish a motion event with sequence number 0.");
657 return BAD_VALUE;
658 }
659
660 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700661 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800662 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700663 return BAD_VALUE;
664 }
665
666 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700667 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500668 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800669 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700670 msg.body.motion.deviceId = deviceId;
671 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700672 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700673 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700674 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100675 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700676 msg.body.motion.flags = flags;
677 msg.body.motion.edgeFlags = edgeFlags;
678 msg.body.motion.metaState = metaState;
679 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800680 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700681 msg.body.motion.dsdx = transform.dsdx();
682 msg.body.motion.dtdx = transform.dtdx();
683 msg.body.motion.dtdy = transform.dtdy();
684 msg.body.motion.dsdy = transform.dsdy();
685 msg.body.motion.tx = transform.tx();
686 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700687 msg.body.motion.xPrecision = xPrecision;
688 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700689 msg.body.motion.xCursorPosition = xCursorPosition;
690 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700691 msg.body.motion.dsdxRaw = rawTransform.dsdx();
692 msg.body.motion.dtdxRaw = rawTransform.dtdx();
693 msg.body.motion.dtdyRaw = rawTransform.dtdy();
694 msg.body.motion.dsdyRaw = rawTransform.dsdy();
695 msg.body.motion.txRaw = rawTransform.tx();
696 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700697 msg.body.motion.downTime = downTime;
698 msg.body.motion.eventTime = eventTime;
699 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100700 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700701 msg.body.motion.pointers[i].properties = pointerProperties[i];
702 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700703 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700704
Jeff Brown5912f952013-07-01 19:10:31 -0700705 return mChannel->sendMessage(&msg);
706}
707
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700708status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000709 ATRACE_NAME_IF(ATRACE_ENABLED(),
710 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
711 mChannel->getName().c_str(), toString(hasFocus)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000712 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
713 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800714
715 InputMessage msg;
716 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500717 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800718 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000719 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800720 return mChannel->sendMessage(&msg);
721}
722
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800723status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
724 bool pointerCaptureEnabled) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000725 ATRACE_NAME_IF(ATRACE_ENABLED(),
726 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
727 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000728 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000729 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
730 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800731
732 InputMessage msg;
733 msg.header.type = InputMessage::Type::CAPTURE;
734 msg.header.seq = seq;
735 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000736 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800737 return mChannel->sendMessage(&msg);
738}
739
arthurhung7632c332020-12-30 16:58:01 +0800740status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
741 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000742 ATRACE_NAME_IF(ATRACE_ENABLED(),
743 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
744 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000745 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000746 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
747 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800748
749 InputMessage msg;
750 msg.header.type = InputMessage::Type::DRAG;
751 msg.header.seq = seq;
752 msg.body.drag.eventId = eventId;
753 msg.body.drag.isExiting = isExiting;
754 msg.body.drag.x = x;
755 msg.body.drag.y = y;
756 return mChannel->sendMessage(&msg);
757}
758
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700759status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000760 ATRACE_NAME_IF(ATRACE_ENABLED(),
761 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
762 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000763 ALOGD_IF(debugTransportPublisher(),
764 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
765 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700766
767 InputMessage msg;
768 msg.header.type = InputMessage::Type::TOUCH_MODE;
769 msg.header.seq = seq;
770 msg.body.touchMode.eventId = eventId;
771 msg.body.touchMode.isInTouchMode = isInTouchMode;
772 return mChannel->sendMessage(&msg);
773}
774
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000775android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700776 InputMessage msg;
777 status_t result = mChannel->receiveMessage(&msg);
778 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700779 if (debugTransportPublisher() && result != WOULD_BLOCK) {
780 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
781 << strerror(result);
782 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000783 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700784 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000785 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000786 ALOGD_IF(debugTransportPublisher(),
787 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
788 mChannel->getName().c_str(), __func__, msg.header.seq,
789 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000790 return Finished{
791 .seq = msg.header.seq,
792 .handled = msg.body.finished.handled,
793 .consumeTime = msg.body.finished.consumeTime,
794 };
Jeff Brown5912f952013-07-01 19:10:31 -0700795 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000796
797 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000798 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
799 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000800 return Timeline{
801 .inputEventId = msg.body.timeline.eventId,
802 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
803 };
804 }
805
806 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800807 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000808 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700809}
810
811// --- InputConsumer ---
812
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500813InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800814 : InputConsumer(channel, isTouchResamplingEnabled()) {}
815
816InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
817 bool enableTouchResampling)
818 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700819
820InputConsumer::~InputConsumer() {
821}
822
823bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600824 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700825}
826
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800827status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
828 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000829 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
830 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
831 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700832
833 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700834 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700835
836 // Fetch the next input message.
837 // Loop until an event can be returned or no additional events are received.
838 while (!*outEvent) {
839 if (mMsgDeferred) {
840 // mMsg contains a valid input message from the previous call to consume
841 // that has not yet been processed.
842 mMsgDeferred = false;
843 } else {
844 // Receive a fresh message.
845 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000846 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800847 const auto [_, inserted] =
848 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
849 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
850 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000851 }
Jeff Brown5912f952013-07-01 19:10:31 -0700852 if (result) {
853 // Consume the next batched event unless batches are being held for later.
854 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800855 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700856 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000857 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
858 "channel '%s' consumer ~ consumed batch event, seq=%u",
859 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700860 break;
861 }
862 }
863 return result;
864 }
865 }
866
867 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700868 case InputMessage::Type::KEY: {
869 KeyEvent* keyEvent = factory->createKeyEvent();
870 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700871
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700872 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500873 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700874 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000875 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
876 "channel '%s' consumer ~ consumed key event, seq=%u",
877 mChannel->getName().c_str(), *outSeq);
878 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700879 }
Jeff Brown5912f952013-07-01 19:10:31 -0700880
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700881 case InputMessage::Type::MOTION: {
882 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
883 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500884 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700885 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500886 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000887 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
888 "channel '%s' consumer ~ appended to batch event",
889 mChannel->getName().c_str());
890 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700891 } else if (isPointerEvent(mMsg.body.motion.source) &&
892 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
893 // No need to process events that we are going to cancel anyways
894 const size_t count = batch.samples.size();
895 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500896 const InputMessage& msg = batch.samples[i];
897 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700898 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500899 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
900 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700901 } else {
902 // We cannot append to the batch in progress, so we need to consume
903 // the previous batch right now and defer the new message until later.
904 mMsgDeferred = true;
905 status_t result = consumeSamples(factory, batch, batch.samples.size(),
906 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500907 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700908 if (result) {
909 return result;
910 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000911 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
912 "channel '%s' consumer ~ consumed batch event and "
913 "deferred current event, seq=%u",
914 mChannel->getName().c_str(), *outSeq);
915 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700916 }
Jeff Brown5912f952013-07-01 19:10:31 -0700917 }
Jeff Brown5912f952013-07-01 19:10:31 -0700918
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800919 // Start a new batch if needed.
920 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
921 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500922 Batch batch;
923 batch.samples.push_back(mMsg);
924 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000925 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
926 "channel '%s' consumer ~ started batch event",
927 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800928 break;
929 }
Jeff Brown5912f952013-07-01 19:10:31 -0700930
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800931 MotionEvent* motionEvent = factory->createMotionEvent();
932 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700933
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800934 updateTouchState(mMsg);
935 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500936 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800937 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800938
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000939 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
940 "channel '%s' consumer ~ consumed motion event, seq=%u",
941 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800942 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700943 }
Jeff Brown5912f952013-07-01 19:10:31 -0700944
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000945 case InputMessage::Type::FINISHED:
946 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000947 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
948 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800949 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800950 break;
951 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800952
953 case InputMessage::Type::FOCUS: {
954 FocusEvent* focusEvent = factory->createFocusEvent();
955 if (!focusEvent) return NO_MEMORY;
956
957 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500958 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800959 *outEvent = focusEvent;
960 break;
961 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800962
963 case InputMessage::Type::CAPTURE: {
964 CaptureEvent* captureEvent = factory->createCaptureEvent();
965 if (!captureEvent) return NO_MEMORY;
966
967 initializeCaptureEvent(captureEvent, &mMsg);
968 *outSeq = mMsg.header.seq;
969 *outEvent = captureEvent;
970 break;
971 }
arthurhung7632c332020-12-30 16:58:01 +0800972
973 case InputMessage::Type::DRAG: {
974 DragEvent* dragEvent = factory->createDragEvent();
975 if (!dragEvent) return NO_MEMORY;
976
977 initializeDragEvent(dragEvent, &mMsg);
978 *outSeq = mMsg.header.seq;
979 *outEvent = dragEvent;
980 break;
981 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700982
983 case InputMessage::Type::TOUCH_MODE: {
984 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
985 if (!touchModeEvent) return NO_MEMORY;
986
987 initializeTouchModeEvent(touchModeEvent, &mMsg);
988 *outSeq = mMsg.header.seq;
989 *outEvent = touchModeEvent;
990 break;
991 }
Jeff Brown5912f952013-07-01 19:10:31 -0700992 }
993 }
994 return OK;
995}
996
997status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800998 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700999 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001000 for (size_t i = mBatches.size(); i > 0; ) {
1001 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001002 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001003 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001004 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001005 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001006 return result;
1007 }
1008
Michael Wright32232172013-10-21 12:05:22 -07001009 nsecs_t sampleTime = frameTime;
1010 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001011 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001012 }
Jeff Brown5912f952013-07-01 19:10:31 -07001013 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1014 if (split < 0) {
1015 continue;
1016 }
1017
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001018 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001019 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001020 if (batch.samples.empty()) {
1021 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001022 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001023 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001025 }
Michael Wright32232172013-10-21 12:05:22 -07001026 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001027 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1028 }
1029 return result;
1030 }
1031
1032 return WOULD_BLOCK;
1033}
1034
1035status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001036 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001037 MotionEvent* motionEvent = factory->createMotionEvent();
1038 if (! motionEvent) return NO_MEMORY;
1039
1040 uint32_t chain = 0;
1041 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001042 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001043 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001044 if (i) {
1045 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001046 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001047 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001048 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001049 addSample(motionEvent, &msg);
1050 } else {
1051 initializeMotionEvent(motionEvent, &msg);
1052 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001053 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001054 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001055 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001056
1057 *outSeq = chain;
1058 *outEvent = motionEvent;
1059 return OK;
1060}
1061
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001062void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001063 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001064 return;
1065 }
1066
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001067 int32_t deviceId = msg.body.motion.deviceId;
1068 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001069
1070 // Update the touch state history to incorporate the new input message.
1071 // If the message is in the past relative to the most recently produced resampled
1072 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001073 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001074 case AMOTION_EVENT_ACTION_DOWN: {
1075 ssize_t index = findTouchState(deviceId, source);
1076 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001078 index = mTouchStates.size() - 1;
1079 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001080 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001081 touchState.initialize(deviceId, source);
1082 touchState.addHistory(msg);
1083 break;
1084 }
1085
1086 case AMOTION_EVENT_ACTION_MOVE: {
1087 ssize_t index = findTouchState(deviceId, source);
1088 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001089 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001090 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001091 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001092 }
1093 break;
1094 }
1095
1096 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1097 ssize_t index = findTouchState(deviceId, source);
1098 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001099 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001100 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001101 rewriteMessage(touchState, msg);
1102 }
1103 break;
1104 }
1105
1106 case AMOTION_EVENT_ACTION_POINTER_UP: {
1107 ssize_t index = findTouchState(deviceId, source);
1108 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001109 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001110 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001111 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001112 }
1113 break;
1114 }
1115
1116 case AMOTION_EVENT_ACTION_SCROLL: {
1117 ssize_t index = findTouchState(deviceId, source);
1118 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001119 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001120 rewriteMessage(touchState, msg);
1121 }
1122 break;
1123 }
1124
1125 case AMOTION_EVENT_ACTION_UP:
1126 case AMOTION_EVENT_ACTION_CANCEL: {
1127 ssize_t index = findTouchState(deviceId, source);
1128 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001129 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001130 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001131 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001132 }
1133 break;
1134 }
1135 }
1136}
1137
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001138/**
1139 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1140 *
1141 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1142 * is in the past relative to msg and the past two events do not contain identical coordinates),
1143 * then invalidate the lastResample data for that pointer.
1144 * If the two past events have identical coordinates, then lastResample data for that pointer will
1145 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1146 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1147 * not equal to x0 is received.
1148 */
1149void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001150 nsecs_t eventTime = msg.body.motion.eventTime;
1151 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1152 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001153 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001154 if (eventTime < state.lastResample.eventTime ||
1155 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001156 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1157 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001158 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001159 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1160 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001161 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1162 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001163 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001164 } else {
1165 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001166 }
Jeff Brown5912f952013-07-01 19:10:31 -07001167 }
1168 }
1169}
1170
1171void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1172 const InputMessage* next) {
1173 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001174 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001175 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1176 return;
1177 }
1178
1179 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1180 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001181 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001182 return;
1183 }
1184
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001185 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001186 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001187 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001188 return;
1189 }
1190
1191 // Ensure that the current sample has all of the pointers that need to be reported.
1192 const History* current = touchState.getHistory(0);
1193 size_t pointerCount = event->getPointerCount();
1194 for (size_t i = 0; i < pointerCount; i++) {
1195 uint32_t id = event->getPointerId(i);
1196 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001197 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001198 return;
1199 }
1200 }
1201
1202 // Find the data to use for resampling.
1203 const History* other;
1204 History future;
1205 float alpha;
1206 if (next) {
1207 // Interpolate between current sample and future sample.
1208 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001209 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001210 other = &future;
1211 nsecs_t delta = future.eventTime - current->eventTime;
1212 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001213 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001214 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001215 return;
1216 }
1217 alpha = float(sampleTime - current->eventTime) / delta;
1218 } else if (touchState.historySize >= 2) {
1219 // Extrapolate future sample using current sample and past sample.
1220 // So other->eventTime <= current->eventTime <= sampleTime.
1221 other = touchState.getHistory(1);
1222 nsecs_t delta = current->eventTime - other->eventTime;
1223 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001224 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001225 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001226 return;
1227 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001228 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001229 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001230 return;
1231 }
1232 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1233 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001234 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001235 "Sample time is too far in the future, adjusting prediction "
1236 "from %" PRId64 " to %" PRId64 " ns.",
1237 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001238 sampleTime = maxPredict;
1239 }
1240 alpha = float(current->eventTime - sampleTime) / delta;
1241 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001242 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001243 return;
1244 }
1245
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001246 if (current->eventTime == sampleTime) {
1247 // Prevents having 2 events with identical times and coordinates.
1248 return;
1249 }
1250
Jeff Brown5912f952013-07-01 19:10:31 -07001251 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001252 History oldLastResample;
1253 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001254 touchState.lastResample.eventTime = sampleTime;
1255 touchState.lastResample.idBits.clear();
1256 for (size_t i = 0; i < pointerCount; i++) {
1257 uint32_t id = event->getPointerId(i);
1258 touchState.lastResample.idToIndex[id] = i;
1259 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001260 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1261 // We maintain the previously resampled value for this pointer (stored in
1262 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1263 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001264 // The isResampled flag isn't cleared as the values don't reflect what the device is
1265 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001266
1267 // We know here that the coordinates for the pointer haven't changed because we
1268 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1269 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001270 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001271 continue;
1272 }
1273
Jeff Brown5912f952013-07-01 19:10:31 -07001274 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1275 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001276 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001277 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001278 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001279 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001280 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001281 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001282 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001283 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001284 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001285 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1286 "other (%0.3f, %0.3f), alpha %0.3f",
1287 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1288 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001289 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001290 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001291 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1292 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001293 }
1294 }
1295
1296 event->addSample(sampleTime, touchState.lastResample.pointers);
1297}
1298
Jeff Brown5912f952013-07-01 19:10:31 -07001299status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001300 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1301 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1302 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001303
1304 if (!seq) {
1305 ALOGE("Attempted to send a finished signal with sequence number 0.");
1306 return BAD_VALUE;
1307 }
1308
1309 // Send finished signals for the batch sequence chain first.
1310 size_t seqChainCount = mSeqChains.size();
1311 if (seqChainCount) {
1312 uint32_t currentSeq = seq;
1313 uint32_t chainSeqs[seqChainCount];
1314 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001315 for (size_t i = seqChainCount; i > 0; ) {
1316 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001317 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001318 if (seqChain.seq == currentSeq) {
1319 currentSeq = seqChain.chain;
1320 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001321 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001322 }
1323 }
1324 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001325 while (!status && chainIndex > 0) {
1326 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001327 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1328 }
1329 if (status) {
1330 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001331 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001332 SeqChain seqChain;
1333 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1334 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001335 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001336 if (!chainIndex) break;
1337 chainIndex--;
1338 }
Jeff Brown5912f952013-07-01 19:10:31 -07001339 return status;
1340 }
1341 }
1342
1343 // Send finished signal for the last message in the batch.
1344 return sendUnchainedFinishedSignal(seq, handled);
1345}
1346
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001347status_t InputConsumer::sendTimeline(int32_t inputEventId,
1348 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001349 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1350 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1351 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1352 mChannel->getName().c_str(), inputEventId,
1353 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1354 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001355
1356 InputMessage msg;
1357 msg.header.type = InputMessage::Type::TIMELINE;
1358 msg.header.seq = 0;
1359 msg.body.timeline.eventId = inputEventId;
1360 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1361 return mChannel->sendMessage(&msg);
1362}
1363
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001364nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1365 auto it = mConsumeTimes.find(seq);
1366 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1367 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1368 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1369 seq);
1370 return it->second;
1371}
1372
1373void InputConsumer::popConsumeTime(uint32_t seq) {
1374 mConsumeTimes.erase(seq);
1375}
1376
Jeff Brown5912f952013-07-01 19:10:31 -07001377status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1378 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001379 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001380 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001381 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001382 msg.body.finished.consumeTime = getConsumeTime(seq);
1383 status_t result = mChannel->sendMessage(&msg);
1384 if (result == OK) {
1385 // Remove the consume time if the socket write succeeded. We will not need to ack this
1386 // message anymore. If the socket write did not succeed, we will try again and will still
1387 // need consume time.
1388 popConsumeTime(seq);
1389 }
1390 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001391}
1392
Jeff Brown5912f952013-07-01 19:10:31 -07001393bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001394 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001395}
1396
Arthur Hungc7812be2020-02-27 22:40:27 +08001397int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001398 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001399 return AINPUT_SOURCE_CLASS_NONE;
1400 }
1401
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001402 const Batch& batch = mBatches[0];
1403 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001404 return head.body.motion.source;
1405}
1406
Jeff Brown5912f952013-07-01 19:10:31 -07001407ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1408 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001409 const Batch& batch = mBatches[i];
1410 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001411 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1412 return i;
1413 }
1414 }
1415 return -1;
1416}
1417
1418ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1419 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001420 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001421 if (touchState.deviceId == deviceId && touchState.source == source) {
1422 return i;
1423 }
1424 }
1425 return -1;
1426}
1427
1428void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001429 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001430 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1431 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1432 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1433 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001434}
1435
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001436void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001437 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001438}
1439
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001440void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001441 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001442}
1443
arthurhung7632c332020-12-30 16:58:01 +08001444void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1445 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1446 msg->body.drag.isExiting);
1447}
1448
Jeff Brown5912f952013-07-01 19:10:31 -07001449void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001450 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001451 PointerProperties pointerProperties[pointerCount];
1452 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001453 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001454 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1455 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001456 }
1457
chaviw9eaa22c2020-07-01 16:21:27 -07001458 ui::Transform transform;
1459 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1460 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001461 ui::Transform displayTransform;
1462 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1463 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1464 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001465 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1466 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1467 msg->body.motion.actionButton, msg->body.motion.flags,
1468 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001469 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1470 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1471 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001472 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1473 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001474}
1475
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001476void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1477 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1478}
1479
Jeff Brown5912f952013-07-01 19:10:31 -07001480void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001481 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001482 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001483 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001484 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001485 }
1486
1487 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1488 event->addSample(msg->body.motion.eventTime, pointerCoords);
1489}
1490
1491bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001492 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001493 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001494 if (head.body.motion.pointerCount != pointerCount
1495 || head.body.motion.action != msg->body.motion.action) {
1496 return false;
1497 }
1498 for (size_t i = 0; i < pointerCount; i++) {
1499 if (head.body.motion.pointers[i].properties
1500 != msg->body.motion.pointers[i].properties) {
1501 return false;
1502 }
1503 }
1504 return true;
1505}
1506
1507ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1508 size_t numSamples = batch.samples.size();
1509 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001510 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001511 index += 1;
1512 }
1513 return ssize_t(index) - 1;
1514}
1515
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001516std::string InputConsumer::dump() const {
1517 std::string out;
1518 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1519 out = out + "mChannel = " + mChannel->getName() + "\n";
1520 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1521 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001522 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001523 }
1524 out += "Batches:\n";
1525 for (const Batch& batch : mBatches) {
1526 out += " Batch:\n";
1527 for (const InputMessage& msg : batch.samples) {
1528 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001529 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001530 switch (msg.header.type) {
1531 case InputMessage::Type::KEY: {
1532 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1533 KeyEvent::actionToString(
1534 msg.body.key.action),
1535 msg.body.key.keyCode);
1536 break;
1537 }
1538 case InputMessage::Type::MOTION: {
1539 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1540 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1541 const float x = msg.body.motion.pointers[i].coords.getX();
1542 const float y = msg.body.motion.pointers[i].coords.getY();
1543 out += android::base::StringPrintf("\n Pointer %" PRIu32
1544 " : x=%.1f y=%.1f",
1545 i, x, y);
1546 }
1547 break;
1548 }
1549 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001550 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1551 toString(msg.body.finished.handled),
1552 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001553 break;
1554 }
1555 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001556 out += android::base::StringPrintf("hasFocus=%s",
1557 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001558 break;
1559 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001560 case InputMessage::Type::CAPTURE: {
1561 out += android::base::StringPrintf("hasCapture=%s",
1562 toString(msg.body.capture
1563 .pointerCaptureEnabled));
1564 break;
1565 }
arthurhung7632c332020-12-30 16:58:01 +08001566 case InputMessage::Type::DRAG: {
1567 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1568 msg.body.drag.x, msg.body.drag.y,
1569 toString(msg.body.drag.isExiting));
1570 break;
1571 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001572 case InputMessage::Type::TIMELINE: {
1573 const nsecs_t gpuCompletedTime =
1574 msg.body.timeline
1575 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1576 const nsecs_t presentTime =
1577 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1578 out += android::base::StringPrintf("inputEventId=%" PRId32
1579 ", gpuCompletedTime=%" PRId64
1580 ", presentTime=%" PRId64,
1581 msg.body.timeline.eventId, gpuCompletedTime,
1582 presentTime);
1583 break;
1584 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001585 case InputMessage::Type::TOUCH_MODE: {
1586 out += android::base::StringPrintf("isInTouchMode=%s",
1587 toString(msg.body.touchMode.isInTouchMode));
1588 break;
1589 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001590 }
1591 out += "\n";
1592 }
1593 }
1594 if (mBatches.empty()) {
1595 out += " <empty>\n";
1596 }
1597 out += "mSeqChains:\n";
1598 for (const SeqChain& chain : mSeqChains) {
1599 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1600 chain.chain);
1601 }
1602 if (mSeqChains.empty()) {
1603 out += " <empty>\n";
1604 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001605 out += "mConsumeTimes:\n";
1606 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1607 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1608 consumeTime);
1609 }
1610 if (mConsumeTimes.empty()) {
1611 out += " <empty>\n";
1612 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001613 return out;
1614}
1615
Jeff Brown5912f952013-07-01 19:10:31 -07001616} // namespace android