blob: 83453af3b6132ef888b70e933ca46eb3fd30f986 [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 {
Chris Ye0783e992020-06-02 21:34:49 -0700450 nWrite = ::send(getFd(), &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 {
Chris Ye0783e992020-06-02 21:34:49 -0700482 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700483 } while (nRead == -1 && errno == EINTR);
484
485 if (nRead < 0) {
486 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000487 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
488 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700489 if (error == EAGAIN || error == EWOULDBLOCK) {
490 return WOULD_BLOCK;
491 }
492 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
493 return DEAD_OBJECT;
494 }
495 return -error;
496 }
497
498 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000499 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
500 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700501 return DEAD_OBJECT;
502 }
503
504 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000505 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700506 return BAD_VALUE;
507 }
508
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000509 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
510 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100511 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000512 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100513 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
514 ", type=0x%" PRIx32 ")",
515 mName.c_str(), msg->header.seq, msg->header.type);
516 ATRACE_NAME(message.c_str());
517 }
Jeff Brown5912f952013-07-01 19:10:31 -0700518 return OK;
519}
520
Egor Paskoa0d32af2023-12-14 17:45:41 +0100521bool InputChannel::probablyHasInput() const {
522 struct pollfd pfds = {.fd = mFd, .events = POLLIN};
523 if (::poll(&pfds, /*nfds=*/1, /*timeout=*/0) <= 0) {
524 // This can be a false negative because EAGAIN and ENOMEM are not handled. The latter should
525 // be extremely rare. The EAGAIN is also unlikely because it happens only when the signal
526 // arrives while the syscall is executed, and the syscall is quick. Hitting EAGAIN too often
527 // would be a sign of having too many signals, which is a bigger performance problem. A
528 // common tradition is to repeat the syscall on each EAGAIN, but it is not necessary here.
529 // In other words, the missing one liner is replaced by a multiline explanation.
530 return false;
531 }
532 // From poll(2): The bits returned in |revents| can include any of those specified in |events|,
533 // or one of the values POLLERR, POLLHUP, or POLLNVAL.
534 return (pfds.revents & POLLIN) != 0;
535}
536
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500537std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700538 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700539 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700540}
541
Garfield Tan15601662020-09-22 15:32:38 -0700542void InputChannel::copyTo(InputChannel& outChannel) const {
543 outChannel.mName = getName();
544 outChannel.mFd = dupFd();
545 outChannel.mToken = getConnectionToken();
546}
547
Chris Ye0783e992020-06-02 21:34:49 -0700548status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500549 if (parcel == nullptr) {
550 ALOGE("%s: Null parcel", __func__);
551 return BAD_VALUE;
552 }
553 return parcel->writeStrongBinder(mToken)
554 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700555}
556
Chris Ye0783e992020-06-02 21:34:49 -0700557status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500558 if (parcel == nullptr) {
559 ALOGE("%s: Null parcel", __func__);
560 return BAD_VALUE;
561 }
562 mToken = parcel->readStrongBinder();
563 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700564}
565
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700566sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500567 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700568}
569
Garfield Tan15601662020-09-22 15:32:38 -0700570base::unique_fd InputChannel::dupFd() const {
571 android::base::unique_fd newFd(::dup(getFd()));
572 if (!newFd.ok()) {
573 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
574 strerror(errno));
575 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
576 // If this process is out of file descriptors, then throwing that might end up exploding
577 // on the other side of a binder call, which isn't really helpful.
578 // Better to just crash here and hope that the FD leak is slow.
579 // Other failures could be client errors, so we still propagate those back to the caller.
580 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
581 getName().c_str());
582 return {};
583 }
584 return newFd;
585}
586
Jeff Brown5912f952013-07-01 19:10:31 -0700587// --- InputPublisher ---
588
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800589InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
590 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700591
592InputPublisher::~InputPublisher() {
593}
594
Garfield Tan1c7bc862020-01-28 13:24:04 -0800595status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
596 int32_t source, int32_t displayId,
597 std::array<uint8_t, 32> hmac, int32_t action,
598 int32_t flags, int32_t keyCode, int32_t scanCode,
599 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
600 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000601 ATRACE_NAME_IF(ATRACE_ENABLED(),
602 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
603 mChannel->getName().c_str(), KeyEvent::actionToString(action),
604 KeyEvent::getLabel(keyCode)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000605 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000606 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000607 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
608 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000609 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000610 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
611 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700612
613 if (!seq) {
614 ALOGE("Attempted to publish a key event with sequence number 0.");
615 return BAD_VALUE;
616 }
617
618 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700619 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500620 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800621 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700622 msg.body.key.deviceId = deviceId;
623 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100624 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700625 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700626 msg.body.key.action = action;
627 msg.body.key.flags = flags;
628 msg.body.key.keyCode = keyCode;
629 msg.body.key.scanCode = scanCode;
630 msg.body.key.metaState = metaState;
631 msg.body.key.repeatCount = repeatCount;
632 msg.body.key.downTime = downTime;
633 msg.body.key.eventTime = eventTime;
634 return mChannel->sendMessage(&msg);
635}
636
637status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800638 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600639 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
640 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700641 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700642 float yPrecision, float xCursorPosition, float yCursorPosition,
643 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700644 uint32_t pointerCount, const PointerProperties* pointerProperties,
645 const PointerCoords* pointerCoords) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000646 ATRACE_NAME_IF(ATRACE_ENABLED(),
647 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
648 mChannel->getName().c_str(),
649 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800650 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700651 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -0700652 mInputVerifier.processMovement(deviceId, source, action, pointerCount,
653 pointerProperties, pointerCoords, flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700654 if (!result.ok()) {
655 LOG(FATAL) << "Bad stream: " << result.error();
656 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800657 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000658 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700659 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700660 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000661 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800662 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000663 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700664 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800665 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700666 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000667 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000668 inputEventSourceToString(source).c_str(), displayId,
669 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
670 metaState, buttonState, motionClassificationToString(classification), xPrecision,
671 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800672 }
Jeff Brown5912f952013-07-01 19:10:31 -0700673
674 if (!seq) {
675 ALOGE("Attempted to publish a motion event with sequence number 0.");
676 return BAD_VALUE;
677 }
678
679 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700680 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800681 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700682 return BAD_VALUE;
683 }
684
685 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700686 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500687 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800688 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700689 msg.body.motion.deviceId = deviceId;
690 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700691 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700692 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700693 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100694 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700695 msg.body.motion.flags = flags;
696 msg.body.motion.edgeFlags = edgeFlags;
697 msg.body.motion.metaState = metaState;
698 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800699 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700700 msg.body.motion.dsdx = transform.dsdx();
701 msg.body.motion.dtdx = transform.dtdx();
702 msg.body.motion.dtdy = transform.dtdy();
703 msg.body.motion.dsdy = transform.dsdy();
704 msg.body.motion.tx = transform.tx();
705 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700706 msg.body.motion.xPrecision = xPrecision;
707 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700708 msg.body.motion.xCursorPosition = xCursorPosition;
709 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700710 msg.body.motion.dsdxRaw = rawTransform.dsdx();
711 msg.body.motion.dtdxRaw = rawTransform.dtdx();
712 msg.body.motion.dtdyRaw = rawTransform.dtdy();
713 msg.body.motion.dsdyRaw = rawTransform.dsdy();
714 msg.body.motion.txRaw = rawTransform.tx();
715 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700716 msg.body.motion.downTime = downTime;
717 msg.body.motion.eventTime = eventTime;
718 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100719 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700720 msg.body.motion.pointers[i].properties = pointerProperties[i];
721 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700722 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700723
Jeff Brown5912f952013-07-01 19:10:31 -0700724 return mChannel->sendMessage(&msg);
725}
726
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700727status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000728 ATRACE_NAME_IF(ATRACE_ENABLED(),
729 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
730 mChannel->getName().c_str(), toString(hasFocus)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000731 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
732 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800733
734 InputMessage msg;
735 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500736 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800737 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000738 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800739 return mChannel->sendMessage(&msg);
740}
741
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800742status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
743 bool pointerCaptureEnabled) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000744 ATRACE_NAME_IF(ATRACE_ENABLED(),
745 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
746 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000747 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000748 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
749 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800750
751 InputMessage msg;
752 msg.header.type = InputMessage::Type::CAPTURE;
753 msg.header.seq = seq;
754 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000755 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800756 return mChannel->sendMessage(&msg);
757}
758
arthurhung7632c332020-12-30 16:58:01 +0800759status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
760 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000761 ATRACE_NAME_IF(ATRACE_ENABLED(),
762 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
763 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000764 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000765 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
766 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800767
768 InputMessage msg;
769 msg.header.type = InputMessage::Type::DRAG;
770 msg.header.seq = seq;
771 msg.body.drag.eventId = eventId;
772 msg.body.drag.isExiting = isExiting;
773 msg.body.drag.x = x;
774 msg.body.drag.y = y;
775 return mChannel->sendMessage(&msg);
776}
777
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700778status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000779 ATRACE_NAME_IF(ATRACE_ENABLED(),
780 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
781 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000782 ALOGD_IF(debugTransportPublisher(),
783 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
784 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700785
786 InputMessage msg;
787 msg.header.type = InputMessage::Type::TOUCH_MODE;
788 msg.header.seq = seq;
789 msg.body.touchMode.eventId = eventId;
790 msg.body.touchMode.isInTouchMode = isInTouchMode;
791 return mChannel->sendMessage(&msg);
792}
793
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000794android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700795 InputMessage msg;
796 status_t result = mChannel->receiveMessage(&msg);
797 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700798 if (debugTransportPublisher() && result != WOULD_BLOCK) {
799 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
800 << strerror(result);
801 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000802 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700803 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000804 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000805 ALOGD_IF(debugTransportPublisher(),
806 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
807 mChannel->getName().c_str(), __func__, msg.header.seq,
808 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809 return Finished{
810 .seq = msg.header.seq,
811 .handled = msg.body.finished.handled,
812 .consumeTime = msg.body.finished.consumeTime,
813 };
Jeff Brown5912f952013-07-01 19:10:31 -0700814 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000815
816 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000817 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
818 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000819 return Timeline{
820 .inputEventId = msg.body.timeline.eventId,
821 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
822 };
823 }
824
825 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800826 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000827 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700828}
829
830// --- InputConsumer ---
831
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500832InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800833 : InputConsumer(channel, isTouchResamplingEnabled()) {}
834
835InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
836 bool enableTouchResampling)
837 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700838
839InputConsumer::~InputConsumer() {
840}
841
842bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600843 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700844}
845
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800846status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
847 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000848 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
849 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
850 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700851
852 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700853 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700854
855 // Fetch the next input message.
856 // Loop until an event can be returned or no additional events are received.
857 while (!*outEvent) {
858 if (mMsgDeferred) {
859 // mMsg contains a valid input message from the previous call to consume
860 // that has not yet been processed.
861 mMsgDeferred = false;
862 } else {
863 // Receive a fresh message.
864 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000865 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800866 const auto [_, inserted] =
867 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
868 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
869 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000870 }
Jeff Brown5912f952013-07-01 19:10:31 -0700871 if (result) {
872 // Consume the next batched event unless batches are being held for later.
873 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800874 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700875 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000876 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
877 "channel '%s' consumer ~ consumed batch event, seq=%u",
878 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700879 break;
880 }
881 }
882 return result;
883 }
884 }
885
886 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700887 case InputMessage::Type::KEY: {
888 KeyEvent* keyEvent = factory->createKeyEvent();
889 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700890
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700891 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500892 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700893 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000894 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
895 "channel '%s' consumer ~ consumed key event, seq=%u",
896 mChannel->getName().c_str(), *outSeq);
897 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700898 }
Jeff Brown5912f952013-07-01 19:10:31 -0700899
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700900 case InputMessage::Type::MOTION: {
901 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
902 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500903 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700904 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500905 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000906 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
907 "channel '%s' consumer ~ appended to batch event",
908 mChannel->getName().c_str());
909 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700910 } else if (isPointerEvent(mMsg.body.motion.source) &&
911 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
912 // No need to process events that we are going to cancel anyways
913 const size_t count = batch.samples.size();
914 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500915 const InputMessage& msg = batch.samples[i];
916 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700917 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500918 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
919 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700920 } else {
921 // We cannot append to the batch in progress, so we need to consume
922 // the previous batch right now and defer the new message until later.
923 mMsgDeferred = true;
924 status_t result = consumeSamples(factory, batch, batch.samples.size(),
925 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500926 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700927 if (result) {
928 return result;
929 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000930 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
931 "channel '%s' consumer ~ consumed batch event and "
932 "deferred current event, seq=%u",
933 mChannel->getName().c_str(), *outSeq);
934 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700935 }
Jeff Brown5912f952013-07-01 19:10:31 -0700936 }
Jeff Brown5912f952013-07-01 19:10:31 -0700937
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800938 // Start a new batch if needed.
939 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
940 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500941 Batch batch;
942 batch.samples.push_back(mMsg);
943 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000944 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
945 "channel '%s' consumer ~ started batch event",
946 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800947 break;
948 }
Jeff Brown5912f952013-07-01 19:10:31 -0700949
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800950 MotionEvent* motionEvent = factory->createMotionEvent();
951 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700952
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800953 updateTouchState(mMsg);
954 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500955 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800956 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800957
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000958 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
959 "channel '%s' consumer ~ consumed motion event, seq=%u",
960 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800961 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700962 }
Jeff Brown5912f952013-07-01 19:10:31 -0700963
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000964 case InputMessage::Type::FINISHED:
965 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000966 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
967 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800968 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800969 break;
970 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800971
972 case InputMessage::Type::FOCUS: {
973 FocusEvent* focusEvent = factory->createFocusEvent();
974 if (!focusEvent) return NO_MEMORY;
975
976 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500977 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800978 *outEvent = focusEvent;
979 break;
980 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800981
982 case InputMessage::Type::CAPTURE: {
983 CaptureEvent* captureEvent = factory->createCaptureEvent();
984 if (!captureEvent) return NO_MEMORY;
985
986 initializeCaptureEvent(captureEvent, &mMsg);
987 *outSeq = mMsg.header.seq;
988 *outEvent = captureEvent;
989 break;
990 }
arthurhung7632c332020-12-30 16:58:01 +0800991
992 case InputMessage::Type::DRAG: {
993 DragEvent* dragEvent = factory->createDragEvent();
994 if (!dragEvent) return NO_MEMORY;
995
996 initializeDragEvent(dragEvent, &mMsg);
997 *outSeq = mMsg.header.seq;
998 *outEvent = dragEvent;
999 break;
1000 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001001
1002 case InputMessage::Type::TOUCH_MODE: {
1003 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
1004 if (!touchModeEvent) return NO_MEMORY;
1005
1006 initializeTouchModeEvent(touchModeEvent, &mMsg);
1007 *outSeq = mMsg.header.seq;
1008 *outEvent = touchModeEvent;
1009 break;
1010 }
Jeff Brown5912f952013-07-01 19:10:31 -07001011 }
1012 }
1013 return OK;
1014}
1015
1016status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001017 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001018 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001019 for (size_t i = mBatches.size(); i > 0; ) {
1020 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001021 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001022 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001023 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001025 return result;
1026 }
1027
Michael Wright32232172013-10-21 12:05:22 -07001028 nsecs_t sampleTime = frameTime;
1029 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001030 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001031 }
Jeff Brown5912f952013-07-01 19:10:31 -07001032 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1033 if (split < 0) {
1034 continue;
1035 }
1036
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001037 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001038 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001039 if (batch.samples.empty()) {
1040 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001041 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001042 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001043 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001044 }
Michael Wright32232172013-10-21 12:05:22 -07001045 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001046 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1047 }
1048 return result;
1049 }
1050
1051 return WOULD_BLOCK;
1052}
1053
1054status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001055 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001056 MotionEvent* motionEvent = factory->createMotionEvent();
1057 if (! motionEvent) return NO_MEMORY;
1058
1059 uint32_t chain = 0;
1060 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001061 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001062 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001063 if (i) {
1064 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001065 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001066 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001067 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001068 addSample(motionEvent, &msg);
1069 } else {
1070 initializeMotionEvent(motionEvent, &msg);
1071 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001072 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001073 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001074 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001075
1076 *outSeq = chain;
1077 *outEvent = motionEvent;
1078 return OK;
1079}
1080
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001081void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001082 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001083 return;
1084 }
1085
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001086 int32_t deviceId = msg.body.motion.deviceId;
1087 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001088
1089 // Update the touch state history to incorporate the new input message.
1090 // If the message is in the past relative to the most recently produced resampled
1091 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001092 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001093 case AMOTION_EVENT_ACTION_DOWN: {
1094 ssize_t index = findTouchState(deviceId, source);
1095 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001096 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001097 index = mTouchStates.size() - 1;
1098 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001099 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001100 touchState.initialize(deviceId, source);
1101 touchState.addHistory(msg);
1102 break;
1103 }
1104
1105 case AMOTION_EVENT_ACTION_MOVE: {
1106 ssize_t index = findTouchState(deviceId, source);
1107 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001108 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001109 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001110 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001111 }
1112 break;
1113 }
1114
1115 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1116 ssize_t index = findTouchState(deviceId, source);
1117 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001118 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001119 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001120 rewriteMessage(touchState, msg);
1121 }
1122 break;
1123 }
1124
1125 case AMOTION_EVENT_ACTION_POINTER_UP: {
1126 ssize_t index = findTouchState(deviceId, source);
1127 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001128 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001129 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001130 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001131 }
1132 break;
1133 }
1134
1135 case AMOTION_EVENT_ACTION_SCROLL: {
1136 ssize_t index = findTouchState(deviceId, source);
1137 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001138 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001139 rewriteMessage(touchState, msg);
1140 }
1141 break;
1142 }
1143
1144 case AMOTION_EVENT_ACTION_UP:
1145 case AMOTION_EVENT_ACTION_CANCEL: {
1146 ssize_t index = findTouchState(deviceId, source);
1147 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001148 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001149 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001150 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001151 }
1152 break;
1153 }
1154 }
1155}
1156
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001157/**
1158 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1159 *
1160 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1161 * is in the past relative to msg and the past two events do not contain identical coordinates),
1162 * then invalidate the lastResample data for that pointer.
1163 * If the two past events have identical coordinates, then lastResample data for that pointer will
1164 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1165 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1166 * not equal to x0 is received.
1167 */
1168void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001169 nsecs_t eventTime = msg.body.motion.eventTime;
1170 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1171 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001172 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001173 if (eventTime < state.lastResample.eventTime ||
1174 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001175 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1176 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001177 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001178 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1179 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001180 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1181 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001182 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001183 } else {
1184 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001185 }
Jeff Brown5912f952013-07-01 19:10:31 -07001186 }
1187 }
1188}
1189
1190void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1191 const InputMessage* next) {
1192 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001193 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001194 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1195 return;
1196 }
1197
1198 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1199 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001200 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001201 return;
1202 }
1203
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001204 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001205 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001206 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001207 return;
1208 }
1209
1210 // Ensure that the current sample has all of the pointers that need to be reported.
1211 const History* current = touchState.getHistory(0);
1212 size_t pointerCount = event->getPointerCount();
1213 for (size_t i = 0; i < pointerCount; i++) {
1214 uint32_t id = event->getPointerId(i);
1215 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001216 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001217 return;
1218 }
1219 }
1220
1221 // Find the data to use for resampling.
1222 const History* other;
1223 History future;
1224 float alpha;
1225 if (next) {
1226 // Interpolate between current sample and future sample.
1227 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001228 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001229 other = &future;
1230 nsecs_t delta = future.eventTime - current->eventTime;
1231 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001232 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001233 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001234 return;
1235 }
1236 alpha = float(sampleTime - current->eventTime) / delta;
1237 } else if (touchState.historySize >= 2) {
1238 // Extrapolate future sample using current sample and past sample.
1239 // So other->eventTime <= current->eventTime <= sampleTime.
1240 other = touchState.getHistory(1);
1241 nsecs_t delta = current->eventTime - other->eventTime;
1242 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001243 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001244 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001245 return;
1246 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001247 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001248 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001249 return;
1250 }
1251 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1252 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001253 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001254 "Sample time is too far in the future, adjusting prediction "
1255 "from %" PRId64 " to %" PRId64 " ns.",
1256 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001257 sampleTime = maxPredict;
1258 }
1259 alpha = float(current->eventTime - sampleTime) / delta;
1260 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001261 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001262 return;
1263 }
1264
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001265 if (current->eventTime == sampleTime) {
1266 // Prevents having 2 events with identical times and coordinates.
1267 return;
1268 }
1269
Jeff Brown5912f952013-07-01 19:10:31 -07001270 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001271 History oldLastResample;
1272 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001273 touchState.lastResample.eventTime = sampleTime;
1274 touchState.lastResample.idBits.clear();
1275 for (size_t i = 0; i < pointerCount; i++) {
1276 uint32_t id = event->getPointerId(i);
1277 touchState.lastResample.idToIndex[id] = i;
1278 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001279 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1280 // We maintain the previously resampled value for this pointer (stored in
1281 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1282 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001283 // The isResampled flag isn't cleared as the values don't reflect what the device is
1284 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001285
1286 // We know here that the coordinates for the pointer haven't changed because we
1287 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1288 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001289 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001290 continue;
1291 }
1292
Jeff Brown5912f952013-07-01 19:10:31 -07001293 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1294 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001295 resampledCoords = currentCoords;
Philip Quinn4e955a22023-09-26 12:09:40 -07001296 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001297 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001298 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001299 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001300 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001301 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001302 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Harry Cutts6c658cc2023-08-02 14:40:40 +00001303 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001304 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1305 "other (%0.3f, %0.3f), alpha %0.3f",
1306 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1307 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001308 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001309 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001310 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1311 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001312 }
1313 }
1314
1315 event->addSample(sampleTime, touchState.lastResample.pointers);
1316}
1317
Jeff Brown5912f952013-07-01 19:10:31 -07001318status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001319 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1320 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1321 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001322
1323 if (!seq) {
1324 ALOGE("Attempted to send a finished signal with sequence number 0.");
1325 return BAD_VALUE;
1326 }
1327
1328 // Send finished signals for the batch sequence chain first.
1329 size_t seqChainCount = mSeqChains.size();
1330 if (seqChainCount) {
1331 uint32_t currentSeq = seq;
1332 uint32_t chainSeqs[seqChainCount];
1333 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001334 for (size_t i = seqChainCount; i > 0; ) {
1335 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001336 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001337 if (seqChain.seq == currentSeq) {
1338 currentSeq = seqChain.chain;
1339 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001340 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001341 }
1342 }
1343 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001344 while (!status && chainIndex > 0) {
1345 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001346 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1347 }
1348 if (status) {
1349 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001350 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001351 SeqChain seqChain;
1352 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1353 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001354 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001355 if (!chainIndex) break;
1356 chainIndex--;
1357 }
Jeff Brown5912f952013-07-01 19:10:31 -07001358 return status;
1359 }
1360 }
1361
1362 // Send finished signal for the last message in the batch.
1363 return sendUnchainedFinishedSignal(seq, handled);
1364}
1365
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001366status_t InputConsumer::sendTimeline(int32_t inputEventId,
1367 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001368 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1369 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1370 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1371 mChannel->getName().c_str(), inputEventId,
1372 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1373 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001374
1375 InputMessage msg;
1376 msg.header.type = InputMessage::Type::TIMELINE;
1377 msg.header.seq = 0;
1378 msg.body.timeline.eventId = inputEventId;
1379 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1380 return mChannel->sendMessage(&msg);
1381}
1382
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001383nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1384 auto it = mConsumeTimes.find(seq);
1385 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1386 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1387 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1388 seq);
1389 return it->second;
1390}
1391
1392void InputConsumer::popConsumeTime(uint32_t seq) {
1393 mConsumeTimes.erase(seq);
1394}
1395
Jeff Brown5912f952013-07-01 19:10:31 -07001396status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1397 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001398 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001399 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001400 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001401 msg.body.finished.consumeTime = getConsumeTime(seq);
1402 status_t result = mChannel->sendMessage(&msg);
1403 if (result == OK) {
1404 // Remove the consume time if the socket write succeeded. We will not need to ack this
1405 // message anymore. If the socket write did not succeed, we will try again and will still
1406 // need consume time.
1407 popConsumeTime(seq);
1408 }
1409 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001410}
1411
Jeff Brown5912f952013-07-01 19:10:31 -07001412bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001413 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001414}
1415
Arthur Hungc7812be2020-02-27 22:40:27 +08001416int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001417 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001418 return AINPUT_SOURCE_CLASS_NONE;
1419 }
1420
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001421 const Batch& batch = mBatches[0];
1422 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001423 return head.body.motion.source;
1424}
1425
Egor Paskoa0d32af2023-12-14 17:45:41 +01001426bool InputConsumer::probablyHasInput() const {
1427 return hasPendingBatch() || mChannel->probablyHasInput();
1428}
1429
Jeff Brown5912f952013-07-01 19:10:31 -07001430ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1431 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001432 const Batch& batch = mBatches[i];
1433 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001434 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1435 return i;
1436 }
1437 }
1438 return -1;
1439}
1440
1441ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1442 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001443 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001444 if (touchState.deviceId == deviceId && touchState.source == source) {
1445 return i;
1446 }
1447 }
1448 return -1;
1449}
1450
1451void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001452 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001453 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1454 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1455 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1456 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001457}
1458
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001459void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001460 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001461}
1462
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001463void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001464 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001465}
1466
arthurhung7632c332020-12-30 16:58:01 +08001467void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1468 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1469 msg->body.drag.isExiting);
1470}
1471
Jeff Brown5912f952013-07-01 19:10:31 -07001472void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001473 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001474 PointerProperties pointerProperties[pointerCount];
1475 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001476 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001477 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1478 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001479 }
1480
chaviw9eaa22c2020-07-01 16:21:27 -07001481 ui::Transform transform;
1482 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1483 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001484 ui::Transform displayTransform;
1485 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1486 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1487 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001488 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1489 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1490 msg->body.motion.actionButton, msg->body.motion.flags,
1491 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001492 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1493 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1494 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001495 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1496 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001497}
1498
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001499void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1500 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1501}
1502
Jeff Brown5912f952013-07-01 19:10:31 -07001503void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001504 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001505 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001506 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001507 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001508 }
1509
1510 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1511 event->addSample(msg->body.motion.eventTime, pointerCoords);
1512}
1513
1514bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001515 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001516 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001517 if (head.body.motion.pointerCount != pointerCount
1518 || head.body.motion.action != msg->body.motion.action) {
1519 return false;
1520 }
1521 for (size_t i = 0; i < pointerCount; i++) {
1522 if (head.body.motion.pointers[i].properties
1523 != msg->body.motion.pointers[i].properties) {
1524 return false;
1525 }
1526 }
1527 return true;
1528}
1529
1530ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1531 size_t numSamples = batch.samples.size();
1532 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001533 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001534 index += 1;
1535 }
1536 return ssize_t(index) - 1;
1537}
1538
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001539std::string InputConsumer::dump() const {
1540 std::string out;
1541 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1542 out = out + "mChannel = " + mChannel->getName() + "\n";
1543 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1544 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001545 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001546 }
1547 out += "Batches:\n";
1548 for (const Batch& batch : mBatches) {
1549 out += " Batch:\n";
1550 for (const InputMessage& msg : batch.samples) {
1551 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001552 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001553 switch (msg.header.type) {
1554 case InputMessage::Type::KEY: {
1555 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1556 KeyEvent::actionToString(
1557 msg.body.key.action),
1558 msg.body.key.keyCode);
1559 break;
1560 }
1561 case InputMessage::Type::MOTION: {
1562 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1563 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1564 const float x = msg.body.motion.pointers[i].coords.getX();
1565 const float y = msg.body.motion.pointers[i].coords.getY();
1566 out += android::base::StringPrintf("\n Pointer %" PRIu32
1567 " : x=%.1f y=%.1f",
1568 i, x, y);
1569 }
1570 break;
1571 }
1572 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001573 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1574 toString(msg.body.finished.handled),
1575 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001576 break;
1577 }
1578 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001579 out += android::base::StringPrintf("hasFocus=%s",
1580 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001581 break;
1582 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001583 case InputMessage::Type::CAPTURE: {
1584 out += android::base::StringPrintf("hasCapture=%s",
1585 toString(msg.body.capture
1586 .pointerCaptureEnabled));
1587 break;
1588 }
arthurhung7632c332020-12-30 16:58:01 +08001589 case InputMessage::Type::DRAG: {
1590 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1591 msg.body.drag.x, msg.body.drag.y,
1592 toString(msg.body.drag.isExiting));
1593 break;
1594 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001595 case InputMessage::Type::TIMELINE: {
1596 const nsecs_t gpuCompletedTime =
1597 msg.body.timeline
1598 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1599 const nsecs_t presentTime =
1600 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1601 out += android::base::StringPrintf("inputEventId=%" PRId32
1602 ", gpuCompletedTime=%" PRId64
1603 ", presentTime=%" PRId64,
1604 msg.body.timeline.eventId, gpuCompletedTime,
1605 presentTime);
1606 break;
1607 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001608 case InputMessage::Type::TOUCH_MODE: {
1609 out += android::base::StringPrintf("isInTouchMode=%s",
1610 toString(msg.body.touchMode.isInTouchMode));
1611 break;
1612 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001613 }
1614 out += "\n";
1615 }
1616 }
1617 if (mBatches.empty()) {
1618 out += " <empty>\n";
1619 }
1620 out += "mSeqChains:\n";
1621 for (const SeqChain& chain : mSeqChains) {
1622 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1623 chain.chain);
1624 }
1625 if (mSeqChains.empty()) {
1626 out += " <empty>\n";
1627 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001628 out += "mConsumeTimes:\n";
1629 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1630 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1631 consumeTime);
1632 }
1633 if (mConsumeTimes.empty()) {
1634 out += " <empty>\n";
1635 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001636 return out;
1637}
1638
Jeff Brown5912f952013-07-01 19:10:31 -07001639} // namespace android