blob: fa094df1592ad0a986e161fb55034a10ad87cfa3 [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>
Egor Paskoa0d32af2023-12-14 17:45:41 +010013#include <poll.h>
Jeff Brown5912f952013-07-01 19:10:31 -070014#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070015#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070016#include <unistd.h>
17
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070018#include <android-base/logging.h>
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000019#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000020#include <android-base/stringprintf.h>
21#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000025#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070026
Siarhei Vishniakou96818962023-08-23 10:19:02 -070027#include <com_android_input_flags.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <input/InputTransport.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000029#include <input/TraceTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070030
Siarhei Vishniakou96818962023-08-23 10:19:02 -070031namespace input_flags = com::android::input::flags;
32
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000033namespace {
34
35/**
36 * Log debug messages about channel messages (send message, receive message).
37 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
38 * (requires restart)
39 */
40const bool DEBUG_CHANNEL_MESSAGES =
41 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
42
43/**
44 * Log debug messages whenever InputChannel objects are created/destroyed.
45 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
46 * (requires restart)
47 */
48const bool DEBUG_CHANNEL_LIFECYCLE =
49 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
50
51/**
52 * Log debug messages relating to the consumer end of the transport channel.
53 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
54 */
55
56const bool DEBUG_TRANSPORT_CONSUMER =
57 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
58
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000059const bool IS_DEBUGGABLE_BUILD =
60#if defined(__ANDROID__)
61 android::base::GetBoolProperty("ro.debuggable", false);
62#else
63 true;
64#endif
65
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000066/**
67 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000068 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
69 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
70 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000071 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000072bool debugTransportPublisher() {
73 if (!IS_DEBUGGABLE_BUILD) {
74 static const bool DEBUG_TRANSPORT_PUBLISHER =
75 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
76 return DEBUG_TRANSPORT_PUBLISHER;
77 }
78 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
79}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000080
81/**
82 * Log debug messages about touch event resampling.
Harry Cutts6c658cc2023-08-02 14:40:40 +000083 *
84 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG".
85 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
86 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000087 */
Harry Cutts6c658cc2023-08-02 14:40:40 +000088bool debugResampling() {
89 if (!IS_DEBUGGABLE_BUILD) {
90 static const bool DEBUG_TRANSPORT_RESAMPLING =
91 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
92 ANDROID_LOG_INFO);
93 return DEBUG_TRANSPORT_RESAMPLING;
94 }
95 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
96}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000097
98} // namespace
99
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700100using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +0000101using android::base::StringPrintf;
102
Jeff Brown5912f952013-07-01 19:10:31 -0700103namespace android {
104
105// Socket buffer size. The default is typically about 128KB, which is much larger than
106// we really need. So we make it smaller. It just needs to be big enough to hold
107// a few dozen large multi-finger motion events in the case where an application gets
108// behind processing touches.
109static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
110
111// Nanoseconds per milliseconds.
112static const nsecs_t NANOS_PER_MS = 1000000;
113
114// Latency added during resampling. A few milliseconds doesn't hurt much but
115// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800116const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700117
118// Minimum time difference between consecutive samples before attempting to resample.
119static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
120
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700121// Maximum time difference between consecutive samples before attempting to resample
122// by extrapolation.
123static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
124
Jeff Brown5912f952013-07-01 19:10:31 -0700125// Maximum time to predict forward from the last known state, to avoid predicting too
126// far into the future. This time is further bounded by 50% of the last time delta.
127static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
128
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600129/**
130 * System property for enabling / disabling touch resampling.
131 * Resampling extrapolates / interpolates the reported touch event coordinates to better
132 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
133 * Resampling is not needed (and should be disabled) on hardware that already
134 * has touch events triggered by VSYNC.
135 * Set to "1" to enable resampling (default).
136 * Set to "0" to disable resampling.
137 * Resampling is enabled by default.
138 */
139static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
140
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800141/**
142 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
143 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
144 */
145static bool verifyEvents() {
Siarhei Vishniakou96818962023-08-23 10:19:02 -0700146 return input_flags::enable_outbound_event_verification() ||
147 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800148}
149
Jeff Brown5912f952013-07-01 19:10:31 -0700150template<typename T>
151inline static T min(const T& a, const T& b) {
152 return a < b ? a : b;
153}
154
155inline static float lerp(float a, float b, float alpha) {
156 return a + alpha * (b - a);
157}
158
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800159inline static bool isPointerEvent(int32_t source) {
160 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
161}
162
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800163inline static const char* toString(bool value) {
164 return value ? "true" : "false";
165}
166
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700167static bool shouldResampleTool(ToolType toolType) {
168 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
169}
170
Jeff Brown5912f952013-07-01 19:10:31 -0700171// --- InputMessage ---
172
173bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000174 if (size() != actualSize) {
175 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
176 return false;
177 }
178
179 switch (header.type) {
180 case Type::KEY:
181 return true;
182 case Type::MOTION: {
183 const bool valid =
184 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
185 if (!valid) {
186 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
187 }
188 return valid;
189 }
190 case Type::FINISHED:
191 case Type::FOCUS:
192 case Type::CAPTURE:
193 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700194 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000195 return true;
196 case Type::TIMELINE: {
197 const nsecs_t gpuCompletedTime =
198 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
199 const nsecs_t presentTime =
200 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
201 const bool valid = presentTime > gpuCompletedTime;
202 if (!valid) {
203 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
204 " presentTime = %" PRId64,
205 gpuCompletedTime, presentTime);
206 }
207 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700208 }
209 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000210 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700211 return false;
212}
213
214size_t InputMessage::size() const {
215 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700216 case Type::KEY:
217 return sizeof(Header) + body.key.size();
218 case Type::MOTION:
219 return sizeof(Header) + body.motion.size();
220 case Type::FINISHED:
221 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800222 case Type::FOCUS:
223 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800224 case Type::CAPTURE:
225 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800226 case Type::DRAG:
227 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000228 case Type::TIMELINE:
229 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700230 case Type::TOUCH_MODE:
231 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700232 }
233 return sizeof(Header);
234}
235
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800236/**
237 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
238 * memory to zero, then only copy the valid bytes on a per-field basis.
239 */
240void InputMessage::getSanitizedCopy(InputMessage* msg) const {
241 memset(msg, 0, sizeof(*msg));
242
243 // Write the header
244 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500245 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800246
247 // Write the body
248 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700249 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800250 // int32_t eventId
251 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800252 // nsecs_t eventTime
253 msg->body.key.eventTime = body.key.eventTime;
254 // int32_t deviceId
255 msg->body.key.deviceId = body.key.deviceId;
256 // int32_t source
257 msg->body.key.source = body.key.source;
258 // int32_t displayId
259 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600260 // std::array<uint8_t, 32> hmac
261 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800262 // int32_t action
263 msg->body.key.action = body.key.action;
264 // int32_t flags
265 msg->body.key.flags = body.key.flags;
266 // int32_t keyCode
267 msg->body.key.keyCode = body.key.keyCode;
268 // int32_t scanCode
269 msg->body.key.scanCode = body.key.scanCode;
270 // int32_t metaState
271 msg->body.key.metaState = body.key.metaState;
272 // int32_t repeatCount
273 msg->body.key.repeatCount = body.key.repeatCount;
274 // nsecs_t downTime
275 msg->body.key.downTime = body.key.downTime;
276 break;
277 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700278 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800279 // int32_t eventId
280 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700281 // uint32_t pointerCount
282 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800283 // nsecs_t eventTime
284 msg->body.motion.eventTime = body.motion.eventTime;
285 // int32_t deviceId
286 msg->body.motion.deviceId = body.motion.deviceId;
287 // int32_t source
288 msg->body.motion.source = body.motion.source;
289 // int32_t displayId
290 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600291 // std::array<uint8_t, 32> hmac
292 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800293 // int32_t action
294 msg->body.motion.action = body.motion.action;
295 // int32_t actionButton
296 msg->body.motion.actionButton = body.motion.actionButton;
297 // int32_t flags
298 msg->body.motion.flags = body.motion.flags;
299 // int32_t metaState
300 msg->body.motion.metaState = body.motion.metaState;
301 // int32_t buttonState
302 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800303 // MotionClassification classification
304 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800305 // int32_t edgeFlags
306 msg->body.motion.edgeFlags = body.motion.edgeFlags;
307 // nsecs_t downTime
308 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700309
310 msg->body.motion.dsdx = body.motion.dsdx;
311 msg->body.motion.dtdx = body.motion.dtdx;
312 msg->body.motion.dtdy = body.motion.dtdy;
313 msg->body.motion.dsdy = body.motion.dsdy;
314 msg->body.motion.tx = body.motion.tx;
315 msg->body.motion.ty = body.motion.ty;
316
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800317 // float xPrecision
318 msg->body.motion.xPrecision = body.motion.xPrecision;
319 // float yPrecision
320 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700321 // float xCursorPosition
322 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
323 // float yCursorPosition
324 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700325
326 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
327 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
328 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
329 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
330 msg->body.motion.txRaw = body.motion.txRaw;
331 msg->body.motion.tyRaw = body.motion.tyRaw;
332
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800333 //struct Pointer pointers[MAX_POINTERS]
334 for (size_t i = 0; i < body.motion.pointerCount; i++) {
335 // PointerProperties properties
336 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
337 msg->body.motion.pointers[i].properties.toolType =
338 body.motion.pointers[i].properties.toolType,
339 // PointerCoords coords
340 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
341 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
342 memcpy(&msg->body.motion.pointers[i].coords.values[0],
343 &body.motion.pointers[i].coords.values[0],
344 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800345 msg->body.motion.pointers[i].coords.isResampled =
346 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800347 }
348 break;
349 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700350 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800351 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000352 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800353 break;
354 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800355 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800356 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800357 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800358 break;
359 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800360 case InputMessage::Type::CAPTURE: {
361 msg->body.capture.eventId = body.capture.eventId;
362 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
363 break;
364 }
arthurhung7632c332020-12-30 16:58:01 +0800365 case InputMessage::Type::DRAG: {
366 msg->body.drag.eventId = body.drag.eventId;
367 msg->body.drag.x = body.drag.x;
368 msg->body.drag.y = body.drag.y;
369 msg->body.drag.isExiting = body.drag.isExiting;
370 break;
371 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000372 case InputMessage::Type::TIMELINE: {
373 msg->body.timeline.eventId = body.timeline.eventId;
374 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
375 break;
376 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700377 case InputMessage::Type::TOUCH_MODE: {
378 msg->body.touchMode.eventId = body.touchMode.eventId;
379 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
380 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800381 }
382}
Jeff Brown5912f952013-07-01 19:10:31 -0700383
384// --- InputChannel ---
385
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500386std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500387 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700388 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
389 if (result != 0) {
390 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
391 strerror(errno));
392 return nullptr;
393 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500394 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500395 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700396}
397
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500398InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
399 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000400 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
401 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700402}
403
404InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000405 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
406 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700407}
408
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800409status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500410 std::unique_ptr<InputChannel>& outServerChannel,
411 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700412 int sockets[2];
413 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
414 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000415 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
416 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500417 outServerChannel.reset();
418 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700419 return result;
420 }
421
422 int bufferSize = SOCKET_BUFFER_SIZE;
423 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
424 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
425 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
426 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
427
Siarhei Vishniakou4c155eb2023-06-30 11:47:12 -0700428 sp<IBinder> token = sp<BBinder>::make();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700429
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700430 std::string serverChannelName = name + " (server)";
431 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700432 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700433
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700434 std::string clientChannelName = name + " (client)";
435 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700436 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700437 return OK;
438}
439
440status_t InputChannel::sendMessage(const InputMessage* msg) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000441 ATRACE_NAME_IF(ATRACE_ENABLED(),
442 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32
443 ")",
444 mName.c_str(), msg->header.seq, msg->header.type));
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800445 const size_t msgLength = msg->size();
446 InputMessage cleanMsg;
447 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700448 ssize_t nWrite;
449 do {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800450 nWrite = ::send(getFd().get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700451 } while (nWrite == -1 && errno == EINTR);
452
453 if (nWrite < 0) {
454 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000455 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
456 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700457 if (error == EAGAIN || error == EWOULDBLOCK) {
458 return WOULD_BLOCK;
459 }
460 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
461 return DEAD_OBJECT;
462 }
463 return -error;
464 }
465
466 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000467 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
468 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
469 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700470 return DEAD_OBJECT;
471 }
472
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000473 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
474 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100475
Jeff Brown5912f952013-07-01 19:10:31 -0700476 return OK;
477}
478
479status_t InputChannel::receiveMessage(InputMessage* msg) {
480 ssize_t nRead;
481 do {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800482 nRead = ::recv(getFd().get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700483 } while (nRead == -1 && errno == EINTR);
484
485 if (nRead < 0) {
486 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000487 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
488 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700489 if (error == EAGAIN || error == EWOULDBLOCK) {
490 return WOULD_BLOCK;
491 }
492 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
493 return DEAD_OBJECT;
494 }
495 return -error;
496 }
497
498 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000499 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
500 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700501 return DEAD_OBJECT;
502 }
503
504 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000505 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700506 return BAD_VALUE;
507 }
508
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000509 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
510 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100511 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000512 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100513 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
514 ", type=0x%" PRIx32 ")",
515 mName.c_str(), msg->header.seq, msg->header.type);
516 ATRACE_NAME(message.c_str());
517 }
Jeff Brown5912f952013-07-01 19:10:31 -0700518 return OK;
519}
520
Egor Paskoa0d32af2023-12-14 17:45:41 +0100521bool InputChannel::probablyHasInput() const {
522 struct pollfd pfds = {.fd = mFd, .events = POLLIN};
523 if (::poll(&pfds, /*nfds=*/1, /*timeout=*/0) <= 0) {
524 // This can be a false negative because EAGAIN and ENOMEM are not handled. The latter should
525 // be extremely rare. The EAGAIN is also unlikely because it happens only when the signal
526 // arrives while the syscall is executed, and the syscall is quick. Hitting EAGAIN too often
527 // would be a sign of having too many signals, which is a bigger performance problem. A
528 // common tradition is to repeat the syscall on each EAGAIN, but it is not necessary here.
529 // In other words, the missing one liner is replaced by a multiline explanation.
530 return false;
531 }
532 // From poll(2): The bits returned in |revents| can include any of those specified in |events|,
533 // or one of the values POLLERR, POLLHUP, or POLLNVAL.
534 return (pfds.revents & POLLIN) != 0;
535}
536
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500537std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700538 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700539 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700540}
541
Garfield Tan15601662020-09-22 15:32:38 -0700542void InputChannel::copyTo(InputChannel& outChannel) const {
543 outChannel.mName = getName();
544 outChannel.mFd = dupFd();
545 outChannel.mToken = getConnectionToken();
546}
547
Chris Ye0783e992020-06-02 21:34:49 -0700548status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500549 if (parcel == nullptr) {
550 ALOGE("%s: Null parcel", __func__);
551 return BAD_VALUE;
552 }
553 return parcel->writeStrongBinder(mToken)
554 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700555}
556
Chris Ye0783e992020-06-02 21:34:49 -0700557status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500558 if (parcel == nullptr) {
559 ALOGE("%s: Null parcel", __func__);
560 return BAD_VALUE;
561 }
562 mToken = parcel->readStrongBinder();
563 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700564}
565
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700566sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500567 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700568}
569
Garfield Tan15601662020-09-22 15:32:38 -0700570base::unique_fd InputChannel::dupFd() const {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800571 base::unique_fd newFd(::dup(getFd().get()));
Garfield Tan15601662020-09-22 15:32:38 -0700572 if (!newFd.ok()) {
573 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
574 strerror(errno));
575 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
576 // If this process is out of file descriptors, then throwing that might end up exploding
577 // on the other side of a binder call, which isn't really helpful.
578 // Better to just crash here and hope that the FD leak is slow.
579 // Other failures could be client errors, so we still propagate those back to the caller.
580 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
581 getName().c_str());
582 return {};
583 }
584 return newFd;
585}
586
Jeff Brown5912f952013-07-01 19:10:31 -0700587// --- InputPublisher ---
588
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800589InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
590 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700591
592InputPublisher::~InputPublisher() {
593}
594
Garfield Tan1c7bc862020-01-28 13:24:04 -0800595status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
596 int32_t source, int32_t displayId,
597 std::array<uint8_t, 32> hmac, int32_t action,
598 int32_t flags, int32_t keyCode, int32_t scanCode,
599 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
600 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000601 ATRACE_NAME_IF(ATRACE_ENABLED(),
602 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
603 mChannel->getName().c_str(), KeyEvent::actionToString(action),
604 KeyEvent::getLabel(keyCode)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000605 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000606 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000607 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
608 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000609 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000610 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
611 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700612
613 if (!seq) {
614 ALOGE("Attempted to publish a key event with sequence number 0.");
615 return BAD_VALUE;
616 }
617
618 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700619 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500620 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800621 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700622 msg.body.key.deviceId = deviceId;
623 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100624 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700625 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700626 msg.body.key.action = action;
627 msg.body.key.flags = flags;
628 msg.body.key.keyCode = keyCode;
629 msg.body.key.scanCode = scanCode;
630 msg.body.key.metaState = metaState;
631 msg.body.key.repeatCount = repeatCount;
632 msg.body.key.downTime = downTime;
633 msg.body.key.eventTime = eventTime;
634 return mChannel->sendMessage(&msg);
635}
636
637status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800638 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600639 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
640 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700641 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700642 float yPrecision, float xCursorPosition, float yCursorPosition,
643 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700644 uint32_t pointerCount, const PointerProperties* pointerProperties,
645 const PointerCoords* pointerCoords) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000646 ATRACE_NAME_IF(ATRACE_ENABLED(),
647 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
648 mChannel->getName().c_str(),
649 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800650 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700651 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -0700652 mInputVerifier.processMovement(deviceId, source, action, pointerCount,
653 pointerProperties, pointerCoords, flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700654 if (!result.ok()) {
655 LOG(FATAL) << "Bad stream: " << result.error();
656 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800657 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000658 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700659 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700660 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000661 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800662 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000663 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700664 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800665 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700666 "pointerCount=%" PRIu32 "\n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000667 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000668 inputEventSourceToString(source).c_str(), displayId,
669 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
670 metaState, buttonState, motionClassificationToString(classification), xPrecision,
671 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800672 }
Jeff Brown5912f952013-07-01 19:10:31 -0700673
674 if (!seq) {
675 ALOGE("Attempted to publish a motion event with sequence number 0.");
676 return BAD_VALUE;
677 }
678
679 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700680 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800681 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700682 return BAD_VALUE;
683 }
684
685 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700686 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500687 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800688 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700689 msg.body.motion.deviceId = deviceId;
690 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700691 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700692 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700693 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100694 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700695 msg.body.motion.flags = flags;
696 msg.body.motion.edgeFlags = edgeFlags;
697 msg.body.motion.metaState = metaState;
698 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800699 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700700 msg.body.motion.dsdx = transform.dsdx();
701 msg.body.motion.dtdx = transform.dtdx();
702 msg.body.motion.dtdy = transform.dtdy();
703 msg.body.motion.dsdy = transform.dsdy();
704 msg.body.motion.tx = transform.tx();
705 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700706 msg.body.motion.xPrecision = xPrecision;
707 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700708 msg.body.motion.xCursorPosition = xCursorPosition;
709 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700710 msg.body.motion.dsdxRaw = rawTransform.dsdx();
711 msg.body.motion.dtdxRaw = rawTransform.dtdx();
712 msg.body.motion.dtdyRaw = rawTransform.dtdy();
713 msg.body.motion.dsdyRaw = rawTransform.dsdy();
714 msg.body.motion.txRaw = rawTransform.tx();
715 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700716 msg.body.motion.downTime = downTime;
717 msg.body.motion.eventTime = eventTime;
718 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100719 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700720 msg.body.motion.pointers[i].properties = pointerProperties[i];
721 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700722 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700723
Jeff Brown5912f952013-07-01 19:10:31 -0700724 return mChannel->sendMessage(&msg);
725}
726
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700727status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000728 ATRACE_NAME_IF(ATRACE_ENABLED(),
729 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
730 mChannel->getName().c_str(), toString(hasFocus)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000731 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
732 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800733
734 InputMessage msg;
735 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500736 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800737 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000738 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800739 return mChannel->sendMessage(&msg);
740}
741
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800742status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
743 bool pointerCaptureEnabled) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000744 ATRACE_NAME_IF(ATRACE_ENABLED(),
745 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
746 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000747 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000748 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
749 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800750
751 InputMessage msg;
752 msg.header.type = InputMessage::Type::CAPTURE;
753 msg.header.seq = seq;
754 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000755 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800756 return mChannel->sendMessage(&msg);
757}
758
arthurhung7632c332020-12-30 16:58:01 +0800759status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
760 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000761 ATRACE_NAME_IF(ATRACE_ENABLED(),
762 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
763 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000764 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000765 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
766 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800767
768 InputMessage msg;
769 msg.header.type = InputMessage::Type::DRAG;
770 msg.header.seq = seq;
771 msg.body.drag.eventId = eventId;
772 msg.body.drag.isExiting = isExiting;
773 msg.body.drag.x = x;
774 msg.body.drag.y = y;
775 return mChannel->sendMessage(&msg);
776}
777
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700778status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000779 ATRACE_NAME_IF(ATRACE_ENABLED(),
780 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
781 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000782 ALOGD_IF(debugTransportPublisher(),
783 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
784 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700785
786 InputMessage msg;
787 msg.header.type = InputMessage::Type::TOUCH_MODE;
788 msg.header.seq = seq;
789 msg.body.touchMode.eventId = eventId;
790 msg.body.touchMode.isInTouchMode = isInTouchMode;
791 return mChannel->sendMessage(&msg);
792}
793
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000794android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700795 InputMessage msg;
796 status_t result = mChannel->receiveMessage(&msg);
797 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700798 if (debugTransportPublisher() && result != WOULD_BLOCK) {
799 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
800 << strerror(result);
801 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000802 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700803 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000804 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000805 ALOGD_IF(debugTransportPublisher(),
806 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
807 mChannel->getName().c_str(), __func__, msg.header.seq,
808 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809 return Finished{
810 .seq = msg.header.seq,
811 .handled = msg.body.finished.handled,
812 .consumeTime = msg.body.finished.consumeTime,
813 };
Jeff Brown5912f952013-07-01 19:10:31 -0700814 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000815
816 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000817 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
818 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000819 return Timeline{
820 .inputEventId = msg.body.timeline.eventId,
821 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
822 };
823 }
824
825 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800826 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000827 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700828}
829
830// --- InputConsumer ---
831
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500832InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800833 : InputConsumer(channel, isTouchResamplingEnabled()) {}
834
835InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
836 bool enableTouchResampling)
837 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700838
839InputConsumer::~InputConsumer() {
840}
841
842bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600843 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700844}
845
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800846status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
847 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000848 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
849 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
850 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700851
852 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700853 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700854
855 // Fetch the next input message.
856 // Loop until an event can be returned or no additional events are received.
857 while (!*outEvent) {
858 if (mMsgDeferred) {
859 // mMsg contains a valid input message from the previous call to consume
860 // that has not yet been processed.
861 mMsgDeferred = false;
862 } else {
863 // Receive a fresh message.
864 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000865 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800866 const auto [_, inserted] =
867 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
868 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
869 mMsg.header.seq);
Siarhei Vishniakouca42e0d2024-01-12 12:10:32 -0800870
871 // Trace the event processing timeline - event was just read from the socket
872 ATRACE_ASYNC_BEGIN("InputConsumer processing", /*cookie=*/mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000873 }
Jeff Brown5912f952013-07-01 19:10:31 -0700874 if (result) {
875 // Consume the next batched event unless batches are being held for later.
876 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800877 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700878 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000879 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
880 "channel '%s' consumer ~ consumed batch event, seq=%u",
881 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700882 break;
883 }
884 }
885 return result;
886 }
887 }
888
889 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700890 case InputMessage::Type::KEY: {
891 KeyEvent* keyEvent = factory->createKeyEvent();
892 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700893
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700894 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500895 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700896 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000897 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
898 "channel '%s' consumer ~ consumed key event, seq=%u",
899 mChannel->getName().c_str(), *outSeq);
900 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700901 }
Jeff Brown5912f952013-07-01 19:10:31 -0700902
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700903 case InputMessage::Type::MOTION: {
904 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
905 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500906 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700907 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500908 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000909 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
910 "channel '%s' consumer ~ appended to batch event",
911 mChannel->getName().c_str());
912 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700913 } else if (isPointerEvent(mMsg.body.motion.source) &&
914 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
915 // No need to process events that we are going to cancel anyways
916 const size_t count = batch.samples.size();
917 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500918 const InputMessage& msg = batch.samples[i];
919 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700920 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500921 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
922 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700923 } else {
924 // We cannot append to the batch in progress, so we need to consume
925 // the previous batch right now and defer the new message until later.
926 mMsgDeferred = true;
927 status_t result = consumeSamples(factory, batch, batch.samples.size(),
928 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500929 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700930 if (result) {
931 return result;
932 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000933 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
934 "channel '%s' consumer ~ consumed batch event and "
935 "deferred current event, seq=%u",
936 mChannel->getName().c_str(), *outSeq);
937 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700938 }
Jeff Brown5912f952013-07-01 19:10:31 -0700939 }
Jeff Brown5912f952013-07-01 19:10:31 -0700940
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800941 // Start a new batch if needed.
942 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
943 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500944 Batch batch;
945 batch.samples.push_back(mMsg);
946 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000947 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
948 "channel '%s' consumer ~ started batch event",
949 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800950 break;
951 }
Jeff Brown5912f952013-07-01 19:10:31 -0700952
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800953 MotionEvent* motionEvent = factory->createMotionEvent();
954 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700955
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800956 updateTouchState(mMsg);
957 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500958 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800959 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800960
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000961 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
962 "channel '%s' consumer ~ consumed motion event, seq=%u",
963 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800964 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700965 }
Jeff Brown5912f952013-07-01 19:10:31 -0700966
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000967 case InputMessage::Type::FINISHED:
968 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000969 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
970 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800971 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800972 break;
973 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800974
975 case InputMessage::Type::FOCUS: {
976 FocusEvent* focusEvent = factory->createFocusEvent();
977 if (!focusEvent) return NO_MEMORY;
978
979 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500980 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800981 *outEvent = focusEvent;
982 break;
983 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800984
985 case InputMessage::Type::CAPTURE: {
986 CaptureEvent* captureEvent = factory->createCaptureEvent();
987 if (!captureEvent) return NO_MEMORY;
988
989 initializeCaptureEvent(captureEvent, &mMsg);
990 *outSeq = mMsg.header.seq;
991 *outEvent = captureEvent;
992 break;
993 }
arthurhung7632c332020-12-30 16:58:01 +0800994
995 case InputMessage::Type::DRAG: {
996 DragEvent* dragEvent = factory->createDragEvent();
997 if (!dragEvent) return NO_MEMORY;
998
999 initializeDragEvent(dragEvent, &mMsg);
1000 *outSeq = mMsg.header.seq;
1001 *outEvent = dragEvent;
1002 break;
1003 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001004
1005 case InputMessage::Type::TOUCH_MODE: {
1006 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
1007 if (!touchModeEvent) return NO_MEMORY;
1008
1009 initializeTouchModeEvent(touchModeEvent, &mMsg);
1010 *outSeq = mMsg.header.seq;
1011 *outEvent = touchModeEvent;
1012 break;
1013 }
Jeff Brown5912f952013-07-01 19:10:31 -07001014 }
1015 }
1016 return OK;
1017}
1018
1019status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001020 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001021 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001022 for (size_t i = mBatches.size(); i > 0; ) {
1023 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001025 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001026 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001027 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001028 return result;
1029 }
1030
Michael Wright32232172013-10-21 12:05:22 -07001031 nsecs_t sampleTime = frameTime;
1032 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001033 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001034 }
Jeff Brown5912f952013-07-01 19:10:31 -07001035 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1036 if (split < 0) {
1037 continue;
1038 }
1039
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001040 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001041 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001042 if (batch.samples.empty()) {
1043 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001044 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001045 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001046 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001047 }
Michael Wright32232172013-10-21 12:05:22 -07001048 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001049 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1050 }
1051 return result;
1052 }
1053
1054 return WOULD_BLOCK;
1055}
1056
1057status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001058 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001059 MotionEvent* motionEvent = factory->createMotionEvent();
1060 if (! motionEvent) return NO_MEMORY;
1061
1062 uint32_t chain = 0;
1063 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001064 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001065 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001066 if (i) {
1067 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001068 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001069 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001070 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001071 addSample(motionEvent, &msg);
1072 } else {
1073 initializeMotionEvent(motionEvent, &msg);
1074 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001075 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001076 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001078
1079 *outSeq = chain;
1080 *outEvent = motionEvent;
1081 return OK;
1082}
1083
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001084void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001085 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001086 return;
1087 }
1088
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001089 int32_t deviceId = msg.body.motion.deviceId;
1090 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001091
1092 // Update the touch state history to incorporate the new input message.
1093 // If the message is in the past relative to the most recently produced resampled
1094 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001095 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001096 case AMOTION_EVENT_ACTION_DOWN: {
1097 ssize_t index = findTouchState(deviceId, source);
1098 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001099 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001100 index = mTouchStates.size() - 1;
1101 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001102 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001103 touchState.initialize(deviceId, source);
1104 touchState.addHistory(msg);
1105 break;
1106 }
1107
1108 case AMOTION_EVENT_ACTION_MOVE: {
1109 ssize_t index = findTouchState(deviceId, source);
1110 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001111 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001112 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001113 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001114 }
1115 break;
1116 }
1117
1118 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1119 ssize_t index = findTouchState(deviceId, source);
1120 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001121 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001122 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001123 rewriteMessage(touchState, msg);
1124 }
1125 break;
1126 }
1127
1128 case AMOTION_EVENT_ACTION_POINTER_UP: {
1129 ssize_t index = findTouchState(deviceId, source);
1130 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001131 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001132 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001133 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001134 }
1135 break;
1136 }
1137
1138 case AMOTION_EVENT_ACTION_SCROLL: {
1139 ssize_t index = findTouchState(deviceId, source);
1140 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001141 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001142 rewriteMessage(touchState, msg);
1143 }
1144 break;
1145 }
1146
1147 case AMOTION_EVENT_ACTION_UP:
1148 case AMOTION_EVENT_ACTION_CANCEL: {
1149 ssize_t index = findTouchState(deviceId, source);
1150 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001151 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001152 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001153 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001154 }
1155 break;
1156 }
1157 }
1158}
1159
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001160/**
1161 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1162 *
1163 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1164 * is in the past relative to msg and the past two events do not contain identical coordinates),
1165 * then invalidate the lastResample data for that pointer.
1166 * If the two past events have identical coordinates, then lastResample data for that pointer will
1167 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1168 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1169 * not equal to x0 is received.
1170 */
1171void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001172 nsecs_t eventTime = msg.body.motion.eventTime;
1173 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1174 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001175 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001176 if (eventTime < state.lastResample.eventTime ||
1177 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001178 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1179 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001180 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001181 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1182 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001183 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1184 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001185 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001186 } else {
1187 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001188 }
Jeff Brown5912f952013-07-01 19:10:31 -07001189 }
1190 }
1191}
1192
1193void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1194 const InputMessage* next) {
1195 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001196 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001197 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1198 return;
1199 }
1200
1201 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1202 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001203 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001204 return;
1205 }
1206
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001207 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001208 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001209 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001210 return;
1211 }
1212
1213 // Ensure that the current sample has all of the pointers that need to be reported.
1214 const History* current = touchState.getHistory(0);
1215 size_t pointerCount = event->getPointerCount();
1216 for (size_t i = 0; i < pointerCount; i++) {
1217 uint32_t id = event->getPointerId(i);
1218 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001219 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001220 return;
1221 }
1222 }
1223
1224 // Find the data to use for resampling.
1225 const History* other;
1226 History future;
1227 float alpha;
1228 if (next) {
1229 // Interpolate between current sample and future sample.
1230 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001231 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001232 other = &future;
1233 nsecs_t delta = future.eventTime - current->eventTime;
1234 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001235 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001236 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001237 return;
1238 }
1239 alpha = float(sampleTime - current->eventTime) / delta;
1240 } else if (touchState.historySize >= 2) {
1241 // Extrapolate future sample using current sample and past sample.
1242 // So other->eventTime <= current->eventTime <= sampleTime.
1243 other = touchState.getHistory(1);
1244 nsecs_t delta = current->eventTime - other->eventTime;
1245 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001246 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001247 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001248 return;
1249 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001250 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001251 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001252 return;
1253 }
1254 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1255 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001256 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001257 "Sample time is too far in the future, adjusting prediction "
1258 "from %" PRId64 " to %" PRId64 " ns.",
1259 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001260 sampleTime = maxPredict;
1261 }
1262 alpha = float(current->eventTime - sampleTime) / delta;
1263 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001264 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001265 return;
1266 }
1267
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001268 if (current->eventTime == sampleTime) {
1269 // Prevents having 2 events with identical times and coordinates.
1270 return;
1271 }
1272
Jeff Brown5912f952013-07-01 19:10:31 -07001273 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001274 History oldLastResample;
1275 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001276 touchState.lastResample.eventTime = sampleTime;
1277 touchState.lastResample.idBits.clear();
1278 for (size_t i = 0; i < pointerCount; i++) {
1279 uint32_t id = event->getPointerId(i);
1280 touchState.lastResample.idToIndex[id] = i;
1281 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001282 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1283 // We maintain the previously resampled value for this pointer (stored in
1284 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1285 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001286 // The isResampled flag isn't cleared as the values don't reflect what the device is
1287 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001288
1289 // We know here that the coordinates for the pointer haven't changed because we
1290 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1291 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001292 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001293 continue;
1294 }
1295
Jeff Brown5912f952013-07-01 19:10:31 -07001296 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1297 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001298 resampledCoords = currentCoords;
Philip Quinn4e955a22023-09-26 12:09:40 -07001299 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001300 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001301 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001302 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001303 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001304 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001305 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Harry Cutts6c658cc2023-08-02 14:40:40 +00001306 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001307 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1308 "other (%0.3f, %0.3f), alpha %0.3f",
1309 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1310 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001311 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001312 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001313 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1314 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001315 }
1316 }
1317
1318 event->addSample(sampleTime, touchState.lastResample.pointers);
1319}
1320
Jeff Brown5912f952013-07-01 19:10:31 -07001321status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001322 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1323 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1324 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001325
1326 if (!seq) {
1327 ALOGE("Attempted to send a finished signal with sequence number 0.");
1328 return BAD_VALUE;
1329 }
1330
1331 // Send finished signals for the batch sequence chain first.
1332 size_t seqChainCount = mSeqChains.size();
1333 if (seqChainCount) {
1334 uint32_t currentSeq = seq;
1335 uint32_t chainSeqs[seqChainCount];
1336 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001337 for (size_t i = seqChainCount; i > 0; ) {
1338 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001339 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001340 if (seqChain.seq == currentSeq) {
1341 currentSeq = seqChain.chain;
1342 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001343 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001344 }
1345 }
1346 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001347 while (!status && chainIndex > 0) {
1348 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001349 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1350 }
1351 if (status) {
1352 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001353 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001354 SeqChain seqChain;
1355 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1356 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001357 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001358 if (!chainIndex) break;
1359 chainIndex--;
1360 }
Jeff Brown5912f952013-07-01 19:10:31 -07001361 return status;
1362 }
1363 }
1364
1365 // Send finished signal for the last message in the batch.
1366 return sendUnchainedFinishedSignal(seq, handled);
1367}
1368
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001369status_t InputConsumer::sendTimeline(int32_t inputEventId,
1370 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001371 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1372 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1373 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1374 mChannel->getName().c_str(), inputEventId,
1375 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1376 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001377
1378 InputMessage msg;
1379 msg.header.type = InputMessage::Type::TIMELINE;
1380 msg.header.seq = 0;
1381 msg.body.timeline.eventId = inputEventId;
1382 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1383 return mChannel->sendMessage(&msg);
1384}
1385
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001386nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1387 auto it = mConsumeTimes.find(seq);
1388 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1389 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1390 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1391 seq);
1392 return it->second;
1393}
1394
1395void InputConsumer::popConsumeTime(uint32_t seq) {
1396 mConsumeTimes.erase(seq);
1397}
1398
Jeff Brown5912f952013-07-01 19:10:31 -07001399status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1400 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001401 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001402 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001403 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001404 msg.body.finished.consumeTime = getConsumeTime(seq);
1405 status_t result = mChannel->sendMessage(&msg);
1406 if (result == OK) {
1407 // Remove the consume time if the socket write succeeded. We will not need to ack this
1408 // message anymore. If the socket write did not succeed, we will try again and will still
1409 // need consume time.
1410 popConsumeTime(seq);
Siarhei Vishniakouca42e0d2024-01-12 12:10:32 -08001411
1412 // Trace the event processing timeline - event was just finished
1413 ATRACE_ASYNC_END("InputConsumer processing", /*cookie=*/seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001414 }
1415 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001416}
1417
Jeff Brown5912f952013-07-01 19:10:31 -07001418bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001419 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001420}
1421
Arthur Hungc7812be2020-02-27 22:40:27 +08001422int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001423 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001424 return AINPUT_SOURCE_CLASS_NONE;
1425 }
1426
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001427 const Batch& batch = mBatches[0];
1428 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001429 return head.body.motion.source;
1430}
1431
Egor Paskoa0d32af2023-12-14 17:45:41 +01001432bool InputConsumer::probablyHasInput() const {
1433 return hasPendingBatch() || mChannel->probablyHasInput();
1434}
1435
Jeff Brown5912f952013-07-01 19:10:31 -07001436ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1437 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001438 const Batch& batch = mBatches[i];
1439 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001440 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1441 return i;
1442 }
1443 }
1444 return -1;
1445}
1446
1447ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1448 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001449 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001450 if (touchState.deviceId == deviceId && touchState.source == source) {
1451 return i;
1452 }
1453 }
1454 return -1;
1455}
1456
1457void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001458 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001459 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1460 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1461 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1462 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001463}
1464
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001465void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001466 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001467}
1468
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001469void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001470 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001471}
1472
arthurhung7632c332020-12-30 16:58:01 +08001473void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1474 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1475 msg->body.drag.isExiting);
1476}
1477
Jeff Brown5912f952013-07-01 19:10:31 -07001478void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001479 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001480 PointerProperties pointerProperties[pointerCount];
1481 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001482 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001483 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1484 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001485 }
1486
chaviw9eaa22c2020-07-01 16:21:27 -07001487 ui::Transform transform;
1488 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1489 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001490 ui::Transform displayTransform;
1491 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1492 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1493 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001494 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1495 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1496 msg->body.motion.actionButton, msg->body.motion.flags,
1497 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001498 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1499 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1500 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001501 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1502 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001503}
1504
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001505void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1506 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1507}
1508
Jeff Brown5912f952013-07-01 19:10:31 -07001509void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001510 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001511 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001512 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001513 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001514 }
1515
1516 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1517 event->addSample(msg->body.motion.eventTime, pointerCoords);
1518}
1519
1520bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001521 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001522 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001523 if (head.body.motion.pointerCount != pointerCount
1524 || head.body.motion.action != msg->body.motion.action) {
1525 return false;
1526 }
1527 for (size_t i = 0; i < pointerCount; i++) {
1528 if (head.body.motion.pointers[i].properties
1529 != msg->body.motion.pointers[i].properties) {
1530 return false;
1531 }
1532 }
1533 return true;
1534}
1535
1536ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1537 size_t numSamples = batch.samples.size();
1538 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001539 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001540 index += 1;
1541 }
1542 return ssize_t(index) - 1;
1543}
1544
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001545std::string InputConsumer::dump() const {
1546 std::string out;
1547 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1548 out = out + "mChannel = " + mChannel->getName() + "\n";
1549 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1550 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001551 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001552 }
1553 out += "Batches:\n";
1554 for (const Batch& batch : mBatches) {
1555 out += " Batch:\n";
1556 for (const InputMessage& msg : batch.samples) {
1557 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001558 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001559 switch (msg.header.type) {
1560 case InputMessage::Type::KEY: {
1561 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1562 KeyEvent::actionToString(
1563 msg.body.key.action),
1564 msg.body.key.keyCode);
1565 break;
1566 }
1567 case InputMessage::Type::MOTION: {
1568 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1569 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1570 const float x = msg.body.motion.pointers[i].coords.getX();
1571 const float y = msg.body.motion.pointers[i].coords.getY();
1572 out += android::base::StringPrintf("\n Pointer %" PRIu32
1573 " : x=%.1f y=%.1f",
1574 i, x, y);
1575 }
1576 break;
1577 }
1578 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001579 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1580 toString(msg.body.finished.handled),
1581 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001582 break;
1583 }
1584 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001585 out += android::base::StringPrintf("hasFocus=%s",
1586 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001587 break;
1588 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001589 case InputMessage::Type::CAPTURE: {
1590 out += android::base::StringPrintf("hasCapture=%s",
1591 toString(msg.body.capture
1592 .pointerCaptureEnabled));
1593 break;
1594 }
arthurhung7632c332020-12-30 16:58:01 +08001595 case InputMessage::Type::DRAG: {
1596 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1597 msg.body.drag.x, msg.body.drag.y,
1598 toString(msg.body.drag.isExiting));
1599 break;
1600 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001601 case InputMessage::Type::TIMELINE: {
1602 const nsecs_t gpuCompletedTime =
1603 msg.body.timeline
1604 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1605 const nsecs_t presentTime =
1606 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1607 out += android::base::StringPrintf("inputEventId=%" PRId32
1608 ", gpuCompletedTime=%" PRId64
1609 ", presentTime=%" PRId64,
1610 msg.body.timeline.eventId, gpuCompletedTime,
1611 presentTime);
1612 break;
1613 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001614 case InputMessage::Type::TOUCH_MODE: {
1615 out += android::base::StringPrintf("isInTouchMode=%s",
1616 toString(msg.body.touchMode.isInTouchMode));
1617 break;
1618 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001619 }
1620 out += "\n";
1621 }
1622 }
1623 if (mBatches.empty()) {
1624 out += " <empty>\n";
1625 }
1626 out += "mSeqChains:\n";
1627 for (const SeqChain& chain : mSeqChains) {
1628 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1629 chain.chain);
1630 }
1631 if (mSeqChains.empty()) {
1632 out += " <empty>\n";
1633 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001634 out += "mConsumeTimes:\n";
1635 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1636 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1637 consumeTime);
1638 }
1639 if (mConsumeTimes.empty()) {
1640 out += " <empty>\n";
1641 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001642 return out;
1643}
1644
Jeff Brown5912f952013-07-01 19:10:31 -07001645} // namespace android