blob: e63b8f012fb8d3fbcf133c6667104fb1be5c9cf2 [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) {
Egor Pasko5a67a562024-01-16 16:46:45 +0100524 // This can be a false negative because EINTR and ENOMEM are not handled. The latter should
525 // be extremely rare. The EINTR is also unlikely because it happens only when the signal
526 // arrives while the syscall is executed, and the syscall is quick. Hitting EINTR too often
Egor Paskoa0d32af2023-12-14 17:45:41 +0100527 // would be a sign of having too many signals, which is a bigger performance problem. A
Egor Pasko5a67a562024-01-16 16:46:45 +0100528 // common tradition is to repeat the syscall on each EINTR, but it is not necessary here.
Egor Paskoa0d32af2023-12-14 17:45:41 +0100529 // 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
Egor Pasko5a67a562024-01-16 16:46:45 +0100537void InputChannel::waitForMessage(std::chrono::milliseconds timeout) const {
538 if (timeout < 0ms) {
539 LOG(FATAL) << "Timeout cannot be negative, received " << timeout.count();
540 }
541 struct pollfd pfds = {.fd = mFd, .events = POLLIN};
542 int ret;
543 std::chrono::time_point<std::chrono::steady_clock> stopTime =
544 std::chrono::steady_clock::now() + timeout;
545 std::chrono::milliseconds remaining = timeout;
546 do {
547 ret = ::poll(&pfds, /*nfds=*/1, /*timeout=*/remaining.count());
548 remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
549 stopTime - std::chrono::steady_clock::now());
550 } while (ret == -1 && errno == EINTR && remaining > 0ms);
551}
552
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500553std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700554 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700555 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700556}
557
Garfield Tan15601662020-09-22 15:32:38 -0700558void InputChannel::copyTo(InputChannel& outChannel) const {
559 outChannel.mName = getName();
560 outChannel.mFd = dupFd();
561 outChannel.mToken = getConnectionToken();
562}
563
Chris Ye0783e992020-06-02 21:34:49 -0700564status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500565 if (parcel == nullptr) {
566 ALOGE("%s: Null parcel", __func__);
567 return BAD_VALUE;
568 }
569 return parcel->writeStrongBinder(mToken)
570 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700571}
572
Chris Ye0783e992020-06-02 21:34:49 -0700573status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500574 if (parcel == nullptr) {
575 ALOGE("%s: Null parcel", __func__);
576 return BAD_VALUE;
577 }
578 mToken = parcel->readStrongBinder();
579 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700580}
581
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700582sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500583 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700584}
585
Garfield Tan15601662020-09-22 15:32:38 -0700586base::unique_fd InputChannel::dupFd() const {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800587 base::unique_fd newFd(::dup(getFd().get()));
Garfield Tan15601662020-09-22 15:32:38 -0700588 if (!newFd.ok()) {
589 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
590 strerror(errno));
591 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
592 // If this process is out of file descriptors, then throwing that might end up exploding
593 // on the other side of a binder call, which isn't really helpful.
594 // Better to just crash here and hope that the FD leak is slow.
595 // Other failures could be client errors, so we still propagate those back to the caller.
596 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
597 getName().c_str());
598 return {};
599 }
600 return newFd;
601}
602
Jeff Brown5912f952013-07-01 19:10:31 -0700603// --- InputPublisher ---
604
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800605InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
606 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700607
608InputPublisher::~InputPublisher() {
609}
610
Garfield Tan1c7bc862020-01-28 13:24:04 -0800611status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
612 int32_t source, int32_t displayId,
613 std::array<uint8_t, 32> hmac, int32_t action,
614 int32_t flags, int32_t keyCode, int32_t scanCode,
615 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
616 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000617 ATRACE_NAME_IF(ATRACE_ENABLED(),
618 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
619 mChannel->getName().c_str(), KeyEvent::actionToString(action),
620 KeyEvent::getLabel(keyCode)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000621 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000622 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000623 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
624 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000625 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000626 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
627 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700628
629 if (!seq) {
630 ALOGE("Attempted to publish a key event with sequence number 0.");
631 return BAD_VALUE;
632 }
633
634 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700635 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500636 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800637 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700638 msg.body.key.deviceId = deviceId;
639 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100640 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700641 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700642 msg.body.key.action = action;
643 msg.body.key.flags = flags;
644 msg.body.key.keyCode = keyCode;
645 msg.body.key.scanCode = scanCode;
646 msg.body.key.metaState = metaState;
647 msg.body.key.repeatCount = repeatCount;
648 msg.body.key.downTime = downTime;
649 msg.body.key.eventTime = eventTime;
650 return mChannel->sendMessage(&msg);
651}
652
653status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800654 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600655 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
656 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700657 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700658 float yPrecision, float xCursorPosition, float yCursorPosition,
659 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700660 uint32_t pointerCount, const PointerProperties* pointerProperties,
661 const PointerCoords* pointerCoords) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000662 ATRACE_NAME_IF(ATRACE_ENABLED(),
663 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
664 mChannel->getName().c_str(),
665 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800666 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700667 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -0700668 mInputVerifier.processMovement(deviceId, source, action, pointerCount,
669 pointerProperties, pointerCoords, flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700670 if (!result.ok()) {
671 LOG(FATAL) << "Bad stream: " << result.error();
672 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800673 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000674 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700675 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700676 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000677 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800678 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000679 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700680 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800681 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700682 "pointerCount=%" PRIu32 "\n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000683 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000684 inputEventSourceToString(source).c_str(), displayId,
685 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
686 metaState, buttonState, motionClassificationToString(classification), xPrecision,
687 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800688 }
Jeff Brown5912f952013-07-01 19:10:31 -0700689
690 if (!seq) {
691 ALOGE("Attempted to publish a motion event with sequence number 0.");
692 return BAD_VALUE;
693 }
694
695 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700696 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800697 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700698 return BAD_VALUE;
699 }
700
701 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700702 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500703 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800704 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700705 msg.body.motion.deviceId = deviceId;
706 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700707 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700708 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700709 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100710 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700711 msg.body.motion.flags = flags;
712 msg.body.motion.edgeFlags = edgeFlags;
713 msg.body.motion.metaState = metaState;
714 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800715 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700716 msg.body.motion.dsdx = transform.dsdx();
717 msg.body.motion.dtdx = transform.dtdx();
718 msg.body.motion.dtdy = transform.dtdy();
719 msg.body.motion.dsdy = transform.dsdy();
720 msg.body.motion.tx = transform.tx();
721 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700722 msg.body.motion.xPrecision = xPrecision;
723 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700724 msg.body.motion.xCursorPosition = xCursorPosition;
725 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700726 msg.body.motion.dsdxRaw = rawTransform.dsdx();
727 msg.body.motion.dtdxRaw = rawTransform.dtdx();
728 msg.body.motion.dtdyRaw = rawTransform.dtdy();
729 msg.body.motion.dsdyRaw = rawTransform.dsdy();
730 msg.body.motion.txRaw = rawTransform.tx();
731 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700732 msg.body.motion.downTime = downTime;
733 msg.body.motion.eventTime = eventTime;
734 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100735 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700736 msg.body.motion.pointers[i].properties = pointerProperties[i];
737 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700738 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700739
Jeff Brown5912f952013-07-01 19:10:31 -0700740 return mChannel->sendMessage(&msg);
741}
742
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700743status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000744 ATRACE_NAME_IF(ATRACE_ENABLED(),
745 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
746 mChannel->getName().c_str(), toString(hasFocus)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000747 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
748 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800749
750 InputMessage msg;
751 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500752 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800753 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000754 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800755 return mChannel->sendMessage(&msg);
756}
757
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800758status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
759 bool pointerCaptureEnabled) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000760 ATRACE_NAME_IF(ATRACE_ENABLED(),
761 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
762 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000763 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000764 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
765 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800766
767 InputMessage msg;
768 msg.header.type = InputMessage::Type::CAPTURE;
769 msg.header.seq = seq;
770 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000771 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800772 return mChannel->sendMessage(&msg);
773}
774
arthurhung7632c332020-12-30 16:58:01 +0800775status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
776 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000777 ATRACE_NAME_IF(ATRACE_ENABLED(),
778 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
779 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000780 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000781 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
782 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800783
784 InputMessage msg;
785 msg.header.type = InputMessage::Type::DRAG;
786 msg.header.seq = seq;
787 msg.body.drag.eventId = eventId;
788 msg.body.drag.isExiting = isExiting;
789 msg.body.drag.x = x;
790 msg.body.drag.y = y;
791 return mChannel->sendMessage(&msg);
792}
793
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700794status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000795 ATRACE_NAME_IF(ATRACE_ENABLED(),
796 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
797 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000798 ALOGD_IF(debugTransportPublisher(),
799 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
800 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700801
802 InputMessage msg;
803 msg.header.type = InputMessage::Type::TOUCH_MODE;
804 msg.header.seq = seq;
805 msg.body.touchMode.eventId = eventId;
806 msg.body.touchMode.isInTouchMode = isInTouchMode;
807 return mChannel->sendMessage(&msg);
808}
809
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000810android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700811 InputMessage msg;
812 status_t result = mChannel->receiveMessage(&msg);
813 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700814 if (debugTransportPublisher() && result != WOULD_BLOCK) {
815 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
816 << strerror(result);
817 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000818 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700819 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000820 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000821 ALOGD_IF(debugTransportPublisher(),
822 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
823 mChannel->getName().c_str(), __func__, msg.header.seq,
824 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000825 return Finished{
826 .seq = msg.header.seq,
827 .handled = msg.body.finished.handled,
828 .consumeTime = msg.body.finished.consumeTime,
829 };
Jeff Brown5912f952013-07-01 19:10:31 -0700830 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000831
832 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000833 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
834 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000835 return Timeline{
836 .inputEventId = msg.body.timeline.eventId,
837 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
838 };
839 }
840
841 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800842 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000843 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700844}
845
846// --- InputConsumer ---
847
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500848InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800849 : InputConsumer(channel, isTouchResamplingEnabled()) {}
850
851InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
852 bool enableTouchResampling)
853 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700854
855InputConsumer::~InputConsumer() {
856}
857
858bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600859 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700860}
861
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800862status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
863 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000864 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
865 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
866 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700867
868 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700869 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700870
871 // Fetch the next input message.
872 // Loop until an event can be returned or no additional events are received.
873 while (!*outEvent) {
874 if (mMsgDeferred) {
875 // mMsg contains a valid input message from the previous call to consume
876 // that has not yet been processed.
877 mMsgDeferred = false;
878 } else {
879 // Receive a fresh message.
880 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000881 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800882 const auto [_, inserted] =
883 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
884 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
885 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000886 }
Jeff Brown5912f952013-07-01 19:10:31 -0700887 if (result) {
888 // Consume the next batched event unless batches are being held for later.
889 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800890 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700891 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000892 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
893 "channel '%s' consumer ~ consumed batch event, seq=%u",
894 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700895 break;
896 }
897 }
898 return result;
899 }
900 }
901
902 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700903 case InputMessage::Type::KEY: {
904 KeyEvent* keyEvent = factory->createKeyEvent();
905 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700906
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700907 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500908 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700909 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000910 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
911 "channel '%s' consumer ~ consumed key event, seq=%u",
912 mChannel->getName().c_str(), *outSeq);
913 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700914 }
Jeff Brown5912f952013-07-01 19:10:31 -0700915
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700916 case InputMessage::Type::MOTION: {
917 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
918 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500919 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700920 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500921 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000922 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
923 "channel '%s' consumer ~ appended to batch event",
924 mChannel->getName().c_str());
925 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700926 } else if (isPointerEvent(mMsg.body.motion.source) &&
927 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
928 // No need to process events that we are going to cancel anyways
929 const size_t count = batch.samples.size();
930 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500931 const InputMessage& msg = batch.samples[i];
932 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700933 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500934 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
935 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700936 } else {
937 // We cannot append to the batch in progress, so we need to consume
938 // the previous batch right now and defer the new message until later.
939 mMsgDeferred = true;
940 status_t result = consumeSamples(factory, batch, batch.samples.size(),
941 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500942 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700943 if (result) {
944 return result;
945 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000946 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
947 "channel '%s' consumer ~ consumed batch event and "
948 "deferred current event, seq=%u",
949 mChannel->getName().c_str(), *outSeq);
950 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700951 }
Jeff Brown5912f952013-07-01 19:10:31 -0700952 }
Jeff Brown5912f952013-07-01 19:10:31 -0700953
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800954 // Start a new batch if needed.
955 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
956 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500957 Batch batch;
958 batch.samples.push_back(mMsg);
959 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000960 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
961 "channel '%s' consumer ~ started batch event",
962 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800963 break;
964 }
Jeff Brown5912f952013-07-01 19:10:31 -0700965
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800966 MotionEvent* motionEvent = factory->createMotionEvent();
967 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700968
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800969 updateTouchState(mMsg);
970 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500971 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800972 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800973
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000974 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
975 "channel '%s' consumer ~ consumed motion event, seq=%u",
976 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800977 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700978 }
Jeff Brown5912f952013-07-01 19:10:31 -0700979
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000980 case InputMessage::Type::FINISHED:
981 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000982 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
983 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800984 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800985 break;
986 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800987
988 case InputMessage::Type::FOCUS: {
989 FocusEvent* focusEvent = factory->createFocusEvent();
990 if (!focusEvent) return NO_MEMORY;
991
992 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500993 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800994 *outEvent = focusEvent;
995 break;
996 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800997
998 case InputMessage::Type::CAPTURE: {
999 CaptureEvent* captureEvent = factory->createCaptureEvent();
1000 if (!captureEvent) return NO_MEMORY;
1001
1002 initializeCaptureEvent(captureEvent, &mMsg);
1003 *outSeq = mMsg.header.seq;
1004 *outEvent = captureEvent;
1005 break;
1006 }
arthurhung7632c332020-12-30 16:58:01 +08001007
1008 case InputMessage::Type::DRAG: {
1009 DragEvent* dragEvent = factory->createDragEvent();
1010 if (!dragEvent) return NO_MEMORY;
1011
1012 initializeDragEvent(dragEvent, &mMsg);
1013 *outSeq = mMsg.header.seq;
1014 *outEvent = dragEvent;
1015 break;
1016 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001017
1018 case InputMessage::Type::TOUCH_MODE: {
1019 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
1020 if (!touchModeEvent) return NO_MEMORY;
1021
1022 initializeTouchModeEvent(touchModeEvent, &mMsg);
1023 *outSeq = mMsg.header.seq;
1024 *outEvent = touchModeEvent;
1025 break;
1026 }
Jeff Brown5912f952013-07-01 19:10:31 -07001027 }
1028 }
1029 return OK;
1030}
1031
1032status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001033 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001034 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001035 for (size_t i = mBatches.size(); i > 0; ) {
1036 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001037 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001038 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001039 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001040 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001041 return result;
1042 }
1043
Michael Wright32232172013-10-21 12:05:22 -07001044 nsecs_t sampleTime = frameTime;
1045 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001046 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001047 }
Jeff Brown5912f952013-07-01 19:10:31 -07001048 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1049 if (split < 0) {
1050 continue;
1051 }
1052
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001053 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001054 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001055 if (batch.samples.empty()) {
1056 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001057 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001058 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001059 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001060 }
Michael Wright32232172013-10-21 12:05:22 -07001061 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001062 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1063 }
1064 return result;
1065 }
1066
1067 return WOULD_BLOCK;
1068}
1069
1070status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001071 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001072 MotionEvent* motionEvent = factory->createMotionEvent();
1073 if (! motionEvent) return NO_MEMORY;
1074
1075 uint32_t chain = 0;
1076 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001078 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001079 if (i) {
1080 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001081 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001082 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001083 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001084 addSample(motionEvent, &msg);
1085 } else {
1086 initializeMotionEvent(motionEvent, &msg);
1087 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001088 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001089 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001090 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001091
1092 *outSeq = chain;
1093 *outEvent = motionEvent;
1094 return OK;
1095}
1096
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001097void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001098 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001099 return;
1100 }
1101
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001102 int32_t deviceId = msg.body.motion.deviceId;
1103 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001104
1105 // Update the touch state history to incorporate the new input message.
1106 // If the message is in the past relative to the most recently produced resampled
1107 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001108 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001109 case AMOTION_EVENT_ACTION_DOWN: {
1110 ssize_t index = findTouchState(deviceId, source);
1111 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001112 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001113 index = mTouchStates.size() - 1;
1114 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001115 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001116 touchState.initialize(deviceId, source);
1117 touchState.addHistory(msg);
1118 break;
1119 }
1120
1121 case AMOTION_EVENT_ACTION_MOVE: {
1122 ssize_t index = findTouchState(deviceId, source);
1123 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001124 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001125 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001126 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001127 }
1128 break;
1129 }
1130
1131 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1132 ssize_t index = findTouchState(deviceId, source);
1133 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001134 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001135 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001136 rewriteMessage(touchState, msg);
1137 }
1138 break;
1139 }
1140
1141 case AMOTION_EVENT_ACTION_POINTER_UP: {
1142 ssize_t index = findTouchState(deviceId, source);
1143 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001144 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001145 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001146 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001147 }
1148 break;
1149 }
1150
1151 case AMOTION_EVENT_ACTION_SCROLL: {
1152 ssize_t index = findTouchState(deviceId, source);
1153 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001154 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001155 rewriteMessage(touchState, msg);
1156 }
1157 break;
1158 }
1159
1160 case AMOTION_EVENT_ACTION_UP:
1161 case AMOTION_EVENT_ACTION_CANCEL: {
1162 ssize_t index = findTouchState(deviceId, source);
1163 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001164 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001165 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001166 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001167 }
1168 break;
1169 }
1170 }
1171}
1172
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001173/**
1174 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1175 *
1176 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1177 * is in the past relative to msg and the past two events do not contain identical coordinates),
1178 * then invalidate the lastResample data for that pointer.
1179 * If the two past events have identical coordinates, then lastResample data for that pointer will
1180 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1181 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1182 * not equal to x0 is received.
1183 */
1184void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001185 nsecs_t eventTime = msg.body.motion.eventTime;
1186 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1187 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001188 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001189 if (eventTime < state.lastResample.eventTime ||
1190 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001191 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1192 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001193 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001194 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1195 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001196 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1197 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001198 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001199 } else {
1200 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001201 }
Jeff Brown5912f952013-07-01 19:10:31 -07001202 }
1203 }
1204}
1205
1206void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1207 const InputMessage* next) {
1208 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001209 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001210 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1211 return;
1212 }
1213
1214 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1215 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001216 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001217 return;
1218 }
1219
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001220 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001221 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001222 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001223 return;
1224 }
1225
1226 // Ensure that the current sample has all of the pointers that need to be reported.
1227 const History* current = touchState.getHistory(0);
1228 size_t pointerCount = event->getPointerCount();
1229 for (size_t i = 0; i < pointerCount; i++) {
1230 uint32_t id = event->getPointerId(i);
1231 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001232 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001233 return;
1234 }
1235 }
1236
1237 // Find the data to use for resampling.
1238 const History* other;
1239 History future;
1240 float alpha;
1241 if (next) {
1242 // Interpolate between current sample and future sample.
1243 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001244 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001245 other = &future;
1246 nsecs_t delta = future.eventTime - current->eventTime;
1247 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001248 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001249 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001250 return;
1251 }
1252 alpha = float(sampleTime - current->eventTime) / delta;
1253 } else if (touchState.historySize >= 2) {
1254 // Extrapolate future sample using current sample and past sample.
1255 // So other->eventTime <= current->eventTime <= sampleTime.
1256 other = touchState.getHistory(1);
1257 nsecs_t delta = current->eventTime - other->eventTime;
1258 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001259 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001260 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001261 return;
1262 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001263 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001264 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001265 return;
1266 }
1267 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1268 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001269 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001270 "Sample time is too far in the future, adjusting prediction "
1271 "from %" PRId64 " to %" PRId64 " ns.",
1272 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001273 sampleTime = maxPredict;
1274 }
1275 alpha = float(current->eventTime - sampleTime) / delta;
1276 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001277 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001278 return;
1279 }
1280
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001281 if (current->eventTime == sampleTime) {
1282 // Prevents having 2 events with identical times and coordinates.
1283 return;
1284 }
1285
Jeff Brown5912f952013-07-01 19:10:31 -07001286 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001287 History oldLastResample;
1288 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001289 touchState.lastResample.eventTime = sampleTime;
1290 touchState.lastResample.idBits.clear();
1291 for (size_t i = 0; i < pointerCount; i++) {
1292 uint32_t id = event->getPointerId(i);
1293 touchState.lastResample.idToIndex[id] = i;
1294 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001295 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1296 // We maintain the previously resampled value for this pointer (stored in
1297 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1298 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001299 // The isResampled flag isn't cleared as the values don't reflect what the device is
1300 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001301
1302 // We know here that the coordinates for the pointer haven't changed because we
1303 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1304 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001305 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001306 continue;
1307 }
1308
Jeff Brown5912f952013-07-01 19:10:31 -07001309 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1310 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001311 resampledCoords = currentCoords;
Philip Quinn4e955a22023-09-26 12:09:40 -07001312 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001313 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001314 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001315 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001316 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001317 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001318 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Harry Cutts6c658cc2023-08-02 14:40:40 +00001319 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001320 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1321 "other (%0.3f, %0.3f), alpha %0.3f",
1322 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1323 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001324 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001325 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001326 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1327 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001328 }
1329 }
1330
1331 event->addSample(sampleTime, touchState.lastResample.pointers);
1332}
1333
Jeff Brown5912f952013-07-01 19:10:31 -07001334status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001335 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1336 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1337 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001338
1339 if (!seq) {
1340 ALOGE("Attempted to send a finished signal with sequence number 0.");
1341 return BAD_VALUE;
1342 }
1343
1344 // Send finished signals for the batch sequence chain first.
1345 size_t seqChainCount = mSeqChains.size();
1346 if (seqChainCount) {
1347 uint32_t currentSeq = seq;
1348 uint32_t chainSeqs[seqChainCount];
1349 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001350 for (size_t i = seqChainCount; i > 0; ) {
1351 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001352 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001353 if (seqChain.seq == currentSeq) {
1354 currentSeq = seqChain.chain;
1355 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001356 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001357 }
1358 }
1359 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001360 while (!status && chainIndex > 0) {
1361 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001362 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1363 }
1364 if (status) {
1365 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001366 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001367 SeqChain seqChain;
1368 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1369 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001370 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001371 if (!chainIndex) break;
1372 chainIndex--;
1373 }
Jeff Brown5912f952013-07-01 19:10:31 -07001374 return status;
1375 }
1376 }
1377
1378 // Send finished signal for the last message in the batch.
1379 return sendUnchainedFinishedSignal(seq, handled);
1380}
1381
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001382status_t InputConsumer::sendTimeline(int32_t inputEventId,
1383 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001384 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1385 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1386 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1387 mChannel->getName().c_str(), inputEventId,
1388 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1389 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001390
1391 InputMessage msg;
1392 msg.header.type = InputMessage::Type::TIMELINE;
1393 msg.header.seq = 0;
1394 msg.body.timeline.eventId = inputEventId;
1395 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1396 return mChannel->sendMessage(&msg);
1397}
1398
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001399nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1400 auto it = mConsumeTimes.find(seq);
1401 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1402 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1403 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1404 seq);
1405 return it->second;
1406}
1407
1408void InputConsumer::popConsumeTime(uint32_t seq) {
1409 mConsumeTimes.erase(seq);
1410}
1411
Jeff Brown5912f952013-07-01 19:10:31 -07001412status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1413 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001414 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001415 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001416 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001417 msg.body.finished.consumeTime = getConsumeTime(seq);
1418 status_t result = mChannel->sendMessage(&msg);
1419 if (result == OK) {
1420 // Remove the consume time if the socket write succeeded. We will not need to ack this
1421 // message anymore. If the socket write did not succeed, we will try again and will still
1422 // need consume time.
1423 popConsumeTime(seq);
1424 }
1425 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001426}
1427
Jeff Brown5912f952013-07-01 19:10:31 -07001428bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001429 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001430}
1431
Arthur Hungc7812be2020-02-27 22:40:27 +08001432int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001433 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001434 return AINPUT_SOURCE_CLASS_NONE;
1435 }
1436
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001437 const Batch& batch = mBatches[0];
1438 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001439 return head.body.motion.source;
1440}
1441
Egor Paskoa0d32af2023-12-14 17:45:41 +01001442bool InputConsumer::probablyHasInput() const {
1443 return hasPendingBatch() || mChannel->probablyHasInput();
1444}
1445
Jeff Brown5912f952013-07-01 19:10:31 -07001446ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1447 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001448 const Batch& batch = mBatches[i];
1449 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001450 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1451 return i;
1452 }
1453 }
1454 return -1;
1455}
1456
1457ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1458 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001459 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001460 if (touchState.deviceId == deviceId && touchState.source == source) {
1461 return i;
1462 }
1463 }
1464 return -1;
1465}
1466
1467void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001468 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001469 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1470 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1471 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1472 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001473}
1474
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001475void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001476 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001477}
1478
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001479void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001480 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001481}
1482
arthurhung7632c332020-12-30 16:58:01 +08001483void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1484 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1485 msg->body.drag.isExiting);
1486}
1487
Jeff Brown5912f952013-07-01 19:10:31 -07001488void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001489 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001490 PointerProperties pointerProperties[pointerCount];
1491 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001492 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001493 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1494 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001495 }
1496
chaviw9eaa22c2020-07-01 16:21:27 -07001497 ui::Transform transform;
1498 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1499 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001500 ui::Transform displayTransform;
1501 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1502 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1503 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001504 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1505 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1506 msg->body.motion.actionButton, msg->body.motion.flags,
1507 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001508 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1509 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1510 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001511 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1512 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001513}
1514
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001515void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1516 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1517}
1518
Jeff Brown5912f952013-07-01 19:10:31 -07001519void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001520 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001521 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001522 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001523 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001524 }
1525
1526 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1527 event->addSample(msg->body.motion.eventTime, pointerCoords);
1528}
1529
1530bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001531 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001532 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001533 if (head.body.motion.pointerCount != pointerCount
1534 || head.body.motion.action != msg->body.motion.action) {
1535 return false;
1536 }
1537 for (size_t i = 0; i < pointerCount; i++) {
1538 if (head.body.motion.pointers[i].properties
1539 != msg->body.motion.pointers[i].properties) {
1540 return false;
1541 }
1542 }
1543 return true;
1544}
1545
1546ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1547 size_t numSamples = batch.samples.size();
1548 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001549 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001550 index += 1;
1551 }
1552 return ssize_t(index) - 1;
1553}
1554
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001555std::string InputConsumer::dump() const {
1556 std::string out;
1557 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1558 out = out + "mChannel = " + mChannel->getName() + "\n";
1559 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1560 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001561 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001562 }
1563 out += "Batches:\n";
1564 for (const Batch& batch : mBatches) {
1565 out += " Batch:\n";
1566 for (const InputMessage& msg : batch.samples) {
1567 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001568 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001569 switch (msg.header.type) {
1570 case InputMessage::Type::KEY: {
1571 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1572 KeyEvent::actionToString(
1573 msg.body.key.action),
1574 msg.body.key.keyCode);
1575 break;
1576 }
1577 case InputMessage::Type::MOTION: {
1578 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1579 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1580 const float x = msg.body.motion.pointers[i].coords.getX();
1581 const float y = msg.body.motion.pointers[i].coords.getY();
1582 out += android::base::StringPrintf("\n Pointer %" PRIu32
1583 " : x=%.1f y=%.1f",
1584 i, x, y);
1585 }
1586 break;
1587 }
1588 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001589 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1590 toString(msg.body.finished.handled),
1591 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001592 break;
1593 }
1594 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001595 out += android::base::StringPrintf("hasFocus=%s",
1596 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001597 break;
1598 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001599 case InputMessage::Type::CAPTURE: {
1600 out += android::base::StringPrintf("hasCapture=%s",
1601 toString(msg.body.capture
1602 .pointerCaptureEnabled));
1603 break;
1604 }
arthurhung7632c332020-12-30 16:58:01 +08001605 case InputMessage::Type::DRAG: {
1606 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1607 msg.body.drag.x, msg.body.drag.y,
1608 toString(msg.body.drag.isExiting));
1609 break;
1610 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001611 case InputMessage::Type::TIMELINE: {
1612 const nsecs_t gpuCompletedTime =
1613 msg.body.timeline
1614 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1615 const nsecs_t presentTime =
1616 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1617 out += android::base::StringPrintf("inputEventId=%" PRId32
1618 ", gpuCompletedTime=%" PRId64
1619 ", presentTime=%" PRId64,
1620 msg.body.timeline.eventId, gpuCompletedTime,
1621 presentTime);
1622 break;
1623 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001624 case InputMessage::Type::TOUCH_MODE: {
1625 out += android::base::StringPrintf("isInTouchMode=%s",
1626 toString(msg.body.touchMode.isInTouchMode));
1627 break;
1628 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001629 }
1630 out += "\n";
1631 }
1632 }
1633 if (mBatches.empty()) {
1634 out += " <empty>\n";
1635 }
1636 out += "mSeqChains:\n";
1637 for (const SeqChain& chain : mSeqChains) {
1638 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1639 chain.chain);
1640 }
1641 if (mSeqChains.empty()) {
1642 out += " <empty>\n";
1643 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001644 out += "mConsumeTimes:\n";
1645 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1646 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1647 consumeTime);
1648 }
1649 if (mConsumeTimes.empty()) {
1650 out += " <empty>\n";
1651 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001652 return out;
1653}
1654
Jeff Brown5912f952013-07-01 19:10:31 -07001655} // namespace android