blob: 37de00cf35212b127af6ea43835c2340c650d995 [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 Vishniakouca42e0d2024-01-12 12:10:32 -0800886
887 // Trace the event processing timeline - event was just read from the socket
888 ATRACE_ASYNC_BEGIN("InputConsumer processing", /*cookie=*/mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000889 }
Jeff Brown5912f952013-07-01 19:10:31 -0700890 if (result) {
891 // Consume the next batched event unless batches are being held for later.
892 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800893 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700894 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000895 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
896 "channel '%s' consumer ~ consumed batch event, seq=%u",
897 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700898 break;
899 }
900 }
901 return result;
902 }
903 }
904
905 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700906 case InputMessage::Type::KEY: {
907 KeyEvent* keyEvent = factory->createKeyEvent();
908 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700909
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700910 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500911 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700912 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000913 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
914 "channel '%s' consumer ~ consumed key event, seq=%u",
915 mChannel->getName().c_str(), *outSeq);
916 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700917 }
Jeff Brown5912f952013-07-01 19:10:31 -0700918
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700919 case InputMessage::Type::MOTION: {
920 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
921 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500922 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700923 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500924 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000925 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
926 "channel '%s' consumer ~ appended to batch event",
927 mChannel->getName().c_str());
928 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700929 } else if (isPointerEvent(mMsg.body.motion.source) &&
930 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
931 // No need to process events that we are going to cancel anyways
932 const size_t count = batch.samples.size();
933 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500934 const InputMessage& msg = batch.samples[i];
935 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700936 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500937 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
938 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700939 } else {
940 // We cannot append to the batch in progress, so we need to consume
941 // the previous batch right now and defer the new message until later.
942 mMsgDeferred = true;
943 status_t result = consumeSamples(factory, batch, batch.samples.size(),
944 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500945 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700946 if (result) {
947 return result;
948 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000949 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
950 "channel '%s' consumer ~ consumed batch event and "
951 "deferred current event, seq=%u",
952 mChannel->getName().c_str(), *outSeq);
953 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700954 }
Jeff Brown5912f952013-07-01 19:10:31 -0700955 }
Jeff Brown5912f952013-07-01 19:10:31 -0700956
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800957 // Start a new batch if needed.
958 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
959 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500960 Batch batch;
961 batch.samples.push_back(mMsg);
962 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000963 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
964 "channel '%s' consumer ~ started batch event",
965 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800966 break;
967 }
Jeff Brown5912f952013-07-01 19:10:31 -0700968
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800969 MotionEvent* motionEvent = factory->createMotionEvent();
970 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700971
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800972 updateTouchState(mMsg);
973 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500974 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800975 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800976
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000977 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
978 "channel '%s' consumer ~ consumed motion event, seq=%u",
979 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800980 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700981 }
Jeff Brown5912f952013-07-01 19:10:31 -0700982
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000983 case InputMessage::Type::FINISHED:
984 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000985 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
986 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800987 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800988 break;
989 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800990
991 case InputMessage::Type::FOCUS: {
992 FocusEvent* focusEvent = factory->createFocusEvent();
993 if (!focusEvent) return NO_MEMORY;
994
995 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500996 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800997 *outEvent = focusEvent;
998 break;
999 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001000
1001 case InputMessage::Type::CAPTURE: {
1002 CaptureEvent* captureEvent = factory->createCaptureEvent();
1003 if (!captureEvent) return NO_MEMORY;
1004
1005 initializeCaptureEvent(captureEvent, &mMsg);
1006 *outSeq = mMsg.header.seq;
1007 *outEvent = captureEvent;
1008 break;
1009 }
arthurhung7632c332020-12-30 16:58:01 +08001010
1011 case InputMessage::Type::DRAG: {
1012 DragEvent* dragEvent = factory->createDragEvent();
1013 if (!dragEvent) return NO_MEMORY;
1014
1015 initializeDragEvent(dragEvent, &mMsg);
1016 *outSeq = mMsg.header.seq;
1017 *outEvent = dragEvent;
1018 break;
1019 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001020
1021 case InputMessage::Type::TOUCH_MODE: {
1022 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
1023 if (!touchModeEvent) return NO_MEMORY;
1024
1025 initializeTouchModeEvent(touchModeEvent, &mMsg);
1026 *outSeq = mMsg.header.seq;
1027 *outEvent = touchModeEvent;
1028 break;
1029 }
Jeff Brown5912f952013-07-01 19:10:31 -07001030 }
1031 }
1032 return OK;
1033}
1034
1035status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001036 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001037 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001038 for (size_t i = mBatches.size(); i > 0; ) {
1039 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001040 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001041 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001042 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001043 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001044 return result;
1045 }
1046
Michael Wright32232172013-10-21 12:05:22 -07001047 nsecs_t sampleTime = frameTime;
1048 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001049 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001050 }
Jeff Brown5912f952013-07-01 19:10:31 -07001051 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1052 if (split < 0) {
1053 continue;
1054 }
1055
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001056 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001057 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001058 if (batch.samples.empty()) {
1059 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001060 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001061 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001062 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001063 }
Michael Wright32232172013-10-21 12:05:22 -07001064 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001065 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1066 }
1067 return result;
1068 }
1069
1070 return WOULD_BLOCK;
1071}
1072
1073status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001074 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001075 MotionEvent* motionEvent = factory->createMotionEvent();
1076 if (! motionEvent) return NO_MEMORY;
1077
1078 uint32_t chain = 0;
1079 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001080 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001081 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001082 if (i) {
1083 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001084 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001085 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001086 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001087 addSample(motionEvent, &msg);
1088 } else {
1089 initializeMotionEvent(motionEvent, &msg);
1090 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001091 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001092 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001093 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001094
1095 *outSeq = chain;
1096 *outEvent = motionEvent;
1097 return OK;
1098}
1099
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001100void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001101 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001102 return;
1103 }
1104
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001105 int32_t deviceId = msg.body.motion.deviceId;
1106 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001107
1108 // Update the touch state history to incorporate the new input message.
1109 // If the message is in the past relative to the most recently produced resampled
1110 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001111 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001112 case AMOTION_EVENT_ACTION_DOWN: {
1113 ssize_t index = findTouchState(deviceId, source);
1114 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001115 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001116 index = mTouchStates.size() - 1;
1117 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001118 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001119 touchState.initialize(deviceId, source);
1120 touchState.addHistory(msg);
1121 break;
1122 }
1123
1124 case AMOTION_EVENT_ACTION_MOVE: {
1125 ssize_t index = findTouchState(deviceId, source);
1126 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001127 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001128 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001129 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001130 }
1131 break;
1132 }
1133
1134 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1135 ssize_t index = findTouchState(deviceId, source);
1136 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001137 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001138 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001139 rewriteMessage(touchState, msg);
1140 }
1141 break;
1142 }
1143
1144 case AMOTION_EVENT_ACTION_POINTER_UP: {
1145 ssize_t index = findTouchState(deviceId, source);
1146 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001147 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001148 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001149 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001150 }
1151 break;
1152 }
1153
1154 case AMOTION_EVENT_ACTION_SCROLL: {
1155 ssize_t index = findTouchState(deviceId, source);
1156 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001157 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001158 rewriteMessage(touchState, msg);
1159 }
1160 break;
1161 }
1162
1163 case AMOTION_EVENT_ACTION_UP:
1164 case AMOTION_EVENT_ACTION_CANCEL: {
1165 ssize_t index = findTouchState(deviceId, source);
1166 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001167 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001168 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001169 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001170 }
1171 break;
1172 }
1173 }
1174}
1175
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001176/**
1177 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1178 *
1179 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1180 * is in the past relative to msg and the past two events do not contain identical coordinates),
1181 * then invalidate the lastResample data for that pointer.
1182 * If the two past events have identical coordinates, then lastResample data for that pointer will
1183 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1184 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1185 * not equal to x0 is received.
1186 */
1187void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001188 nsecs_t eventTime = msg.body.motion.eventTime;
1189 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1190 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001191 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001192 if (eventTime < state.lastResample.eventTime ||
1193 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001194 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1195 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001196 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001197 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1198 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001199 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1200 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001201 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001202 } else {
1203 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001204 }
Jeff Brown5912f952013-07-01 19:10:31 -07001205 }
1206 }
1207}
1208
1209void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1210 const InputMessage* next) {
1211 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001212 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001213 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1214 return;
1215 }
1216
1217 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1218 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001219 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001220 return;
1221 }
1222
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001223 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001224 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001225 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001226 return;
1227 }
1228
1229 // Ensure that the current sample has all of the pointers that need to be reported.
1230 const History* current = touchState.getHistory(0);
1231 size_t pointerCount = event->getPointerCount();
1232 for (size_t i = 0; i < pointerCount; i++) {
1233 uint32_t id = event->getPointerId(i);
1234 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001235 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001236 return;
1237 }
1238 }
1239
1240 // Find the data to use for resampling.
1241 const History* other;
1242 History future;
1243 float alpha;
1244 if (next) {
1245 // Interpolate between current sample and future sample.
1246 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001247 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001248 other = &future;
1249 nsecs_t delta = future.eventTime - current->eventTime;
1250 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001251 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001252 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001253 return;
1254 }
1255 alpha = float(sampleTime - current->eventTime) / delta;
1256 } else if (touchState.historySize >= 2) {
1257 // Extrapolate future sample using current sample and past sample.
1258 // So other->eventTime <= current->eventTime <= sampleTime.
1259 other = touchState.getHistory(1);
1260 nsecs_t delta = current->eventTime - other->eventTime;
1261 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001262 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001263 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001264 return;
1265 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001266 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001267 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001268 return;
1269 }
1270 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1271 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001272 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001273 "Sample time is too far in the future, adjusting prediction "
1274 "from %" PRId64 " to %" PRId64 " ns.",
1275 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001276 sampleTime = maxPredict;
1277 }
1278 alpha = float(current->eventTime - sampleTime) / delta;
1279 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001280 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001281 return;
1282 }
1283
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001284 if (current->eventTime == sampleTime) {
1285 // Prevents having 2 events with identical times and coordinates.
1286 return;
1287 }
1288
Jeff Brown5912f952013-07-01 19:10:31 -07001289 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001290 History oldLastResample;
1291 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001292 touchState.lastResample.eventTime = sampleTime;
1293 touchState.lastResample.idBits.clear();
1294 for (size_t i = 0; i < pointerCount; i++) {
1295 uint32_t id = event->getPointerId(i);
1296 touchState.lastResample.idToIndex[id] = i;
1297 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001298 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1299 // We maintain the previously resampled value for this pointer (stored in
1300 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1301 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001302 // The isResampled flag isn't cleared as the values don't reflect what the device is
1303 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001304
1305 // We know here that the coordinates for the pointer haven't changed because we
1306 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1307 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001308 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001309 continue;
1310 }
1311
Jeff Brown5912f952013-07-01 19:10:31 -07001312 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1313 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001314 resampledCoords = currentCoords;
Philip Quinn4e955a22023-09-26 12:09:40 -07001315 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001316 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001317 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001318 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001319 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001320 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001321 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Harry Cutts6c658cc2023-08-02 14:40:40 +00001322 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001323 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1324 "other (%0.3f, %0.3f), alpha %0.3f",
1325 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1326 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001327 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001328 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001329 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1330 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001331 }
1332 }
1333
1334 event->addSample(sampleTime, touchState.lastResample.pointers);
1335}
1336
Jeff Brown5912f952013-07-01 19:10:31 -07001337status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001338 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1339 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1340 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001341
1342 if (!seq) {
1343 ALOGE("Attempted to send a finished signal with sequence number 0.");
1344 return BAD_VALUE;
1345 }
1346
1347 // Send finished signals for the batch sequence chain first.
1348 size_t seqChainCount = mSeqChains.size();
1349 if (seqChainCount) {
1350 uint32_t currentSeq = seq;
1351 uint32_t chainSeqs[seqChainCount];
1352 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001353 for (size_t i = seqChainCount; i > 0; ) {
1354 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001355 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001356 if (seqChain.seq == currentSeq) {
1357 currentSeq = seqChain.chain;
1358 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001359 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001360 }
1361 }
1362 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001363 while (!status && chainIndex > 0) {
1364 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001365 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1366 }
1367 if (status) {
1368 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001369 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001370 SeqChain seqChain;
1371 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1372 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001373 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001374 if (!chainIndex) break;
1375 chainIndex--;
1376 }
Jeff Brown5912f952013-07-01 19:10:31 -07001377 return status;
1378 }
1379 }
1380
1381 // Send finished signal for the last message in the batch.
1382 return sendUnchainedFinishedSignal(seq, handled);
1383}
1384
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001385status_t InputConsumer::sendTimeline(int32_t inputEventId,
1386 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001387 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1388 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1389 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1390 mChannel->getName().c_str(), inputEventId,
1391 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1392 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001393
1394 InputMessage msg;
1395 msg.header.type = InputMessage::Type::TIMELINE;
1396 msg.header.seq = 0;
1397 msg.body.timeline.eventId = inputEventId;
1398 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1399 return mChannel->sendMessage(&msg);
1400}
1401
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001402nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1403 auto it = mConsumeTimes.find(seq);
1404 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1405 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1406 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1407 seq);
1408 return it->second;
1409}
1410
1411void InputConsumer::popConsumeTime(uint32_t seq) {
1412 mConsumeTimes.erase(seq);
1413}
1414
Jeff Brown5912f952013-07-01 19:10:31 -07001415status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1416 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001417 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001418 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001419 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001420 msg.body.finished.consumeTime = getConsumeTime(seq);
1421 status_t result = mChannel->sendMessage(&msg);
1422 if (result == OK) {
1423 // Remove the consume time if the socket write succeeded. We will not need to ack this
1424 // message anymore. If the socket write did not succeed, we will try again and will still
1425 // need consume time.
1426 popConsumeTime(seq);
Siarhei Vishniakouca42e0d2024-01-12 12:10:32 -08001427
1428 // Trace the event processing timeline - event was just finished
1429 ATRACE_ASYNC_END("InputConsumer processing", /*cookie=*/seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001430 }
1431 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001432}
1433
Jeff Brown5912f952013-07-01 19:10:31 -07001434bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001435 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001436}
1437
Arthur Hungc7812be2020-02-27 22:40:27 +08001438int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001439 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001440 return AINPUT_SOURCE_CLASS_NONE;
1441 }
1442
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001443 const Batch& batch = mBatches[0];
1444 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001445 return head.body.motion.source;
1446}
1447
Egor Paskoa0d32af2023-12-14 17:45:41 +01001448bool InputConsumer::probablyHasInput() const {
1449 return hasPendingBatch() || mChannel->probablyHasInput();
1450}
1451
Jeff Brown5912f952013-07-01 19:10:31 -07001452ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1453 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001454 const Batch& batch = mBatches[i];
1455 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001456 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1457 return i;
1458 }
1459 }
1460 return -1;
1461}
1462
1463ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1464 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001465 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001466 if (touchState.deviceId == deviceId && touchState.source == source) {
1467 return i;
1468 }
1469 }
1470 return -1;
1471}
1472
1473void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001474 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001475 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1476 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1477 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1478 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001479}
1480
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001481void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001482 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001483}
1484
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001485void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001486 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001487}
1488
arthurhung7632c332020-12-30 16:58:01 +08001489void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1490 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1491 msg->body.drag.isExiting);
1492}
1493
Jeff Brown5912f952013-07-01 19:10:31 -07001494void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001495 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001496 PointerProperties pointerProperties[pointerCount];
1497 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001498 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001499 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1500 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001501 }
1502
chaviw9eaa22c2020-07-01 16:21:27 -07001503 ui::Transform transform;
1504 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1505 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001506 ui::Transform displayTransform;
1507 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1508 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1509 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001510 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1511 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1512 msg->body.motion.actionButton, msg->body.motion.flags,
1513 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001514 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1515 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1516 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001517 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1518 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001519}
1520
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001521void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1522 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1523}
1524
Jeff Brown5912f952013-07-01 19:10:31 -07001525void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001526 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001527 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001528 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001529 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001530 }
1531
1532 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1533 event->addSample(msg->body.motion.eventTime, pointerCoords);
1534}
1535
1536bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001537 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001538 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001539 if (head.body.motion.pointerCount != pointerCount
1540 || head.body.motion.action != msg->body.motion.action) {
1541 return false;
1542 }
1543 for (size_t i = 0; i < pointerCount; i++) {
1544 if (head.body.motion.pointers[i].properties
1545 != msg->body.motion.pointers[i].properties) {
1546 return false;
1547 }
1548 }
1549 return true;
1550}
1551
1552ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1553 size_t numSamples = batch.samples.size();
1554 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001555 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001556 index += 1;
1557 }
1558 return ssize_t(index) - 1;
1559}
1560
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001561std::string InputConsumer::dump() const {
1562 std::string out;
1563 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1564 out = out + "mChannel = " + mChannel->getName() + "\n";
1565 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1566 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001567 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001568 }
1569 out += "Batches:\n";
1570 for (const Batch& batch : mBatches) {
1571 out += " Batch:\n";
1572 for (const InputMessage& msg : batch.samples) {
1573 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001574 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001575 switch (msg.header.type) {
1576 case InputMessage::Type::KEY: {
1577 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1578 KeyEvent::actionToString(
1579 msg.body.key.action),
1580 msg.body.key.keyCode);
1581 break;
1582 }
1583 case InputMessage::Type::MOTION: {
1584 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1585 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1586 const float x = msg.body.motion.pointers[i].coords.getX();
1587 const float y = msg.body.motion.pointers[i].coords.getY();
1588 out += android::base::StringPrintf("\n Pointer %" PRIu32
1589 " : x=%.1f y=%.1f",
1590 i, x, y);
1591 }
1592 break;
1593 }
1594 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001595 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1596 toString(msg.body.finished.handled),
1597 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001598 break;
1599 }
1600 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001601 out += android::base::StringPrintf("hasFocus=%s",
1602 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001603 break;
1604 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001605 case InputMessage::Type::CAPTURE: {
1606 out += android::base::StringPrintf("hasCapture=%s",
1607 toString(msg.body.capture
1608 .pointerCaptureEnabled));
1609 break;
1610 }
arthurhung7632c332020-12-30 16:58:01 +08001611 case InputMessage::Type::DRAG: {
1612 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1613 msg.body.drag.x, msg.body.drag.y,
1614 toString(msg.body.drag.isExiting));
1615 break;
1616 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001617 case InputMessage::Type::TIMELINE: {
1618 const nsecs_t gpuCompletedTime =
1619 msg.body.timeline
1620 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1621 const nsecs_t presentTime =
1622 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1623 out += android::base::StringPrintf("inputEventId=%" PRId32
1624 ", gpuCompletedTime=%" PRId64
1625 ", presentTime=%" PRId64,
1626 msg.body.timeline.eventId, gpuCompletedTime,
1627 presentTime);
1628 break;
1629 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001630 case InputMessage::Type::TOUCH_MODE: {
1631 out += android::base::StringPrintf("isInTouchMode=%s",
1632 toString(msg.body.touchMode.isInTouchMode));
1633 break;
1634 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001635 }
1636 out += "\n";
1637 }
1638 }
1639 if (mBatches.empty()) {
1640 out += " <empty>\n";
1641 }
1642 out += "mSeqChains:\n";
1643 for (const SeqChain& chain : mSeqChains) {
1644 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1645 chain.chain);
1646 }
1647 if (mSeqChains.empty()) {
1648 out += " <empty>\n";
1649 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001650 out += "mConsumeTimes:\n";
1651 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1652 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1653 consumeTime);
1654 }
1655 if (mConsumeTimes.empty()) {
1656 out += " <empty>\n";
1657 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001658 return out;
1659}
1660
Jeff Brown5912f952013-07-01 19:10:31 -07001661} // namespace android