blob: d3653cfc45a33e44a753e58370a09ac8bbb1bb04 [file] [log] [blame]
Siarhei Vishniakou2b920272024-02-27 19:49:51 -08001/**
2 * Copyright 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Ramireze2bb1872024-08-12 20:21:13 +000017#define LOG_TAG "InputConsumerNoResampling"
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
19
20#include <inttypes.h>
21
22#include <android-base/logging.h>
23#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
25#include <cutils/properties.h>
26#include <ftl/enum.h>
27#include <utils/Trace.h>
28
29#include <com_android_input_flags.h>
30#include <input/InputConsumerNoResampling.h>
31#include <input/PrintTools.h>
32#include <input/TraceTools.h>
33
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080034namespace android {
35
36namespace {
37
Paul Ramirezcd7488c2024-09-13 23:01:12 +000038using std::chrono::nanoseconds;
39
Paul Ramireze37f8342024-08-28 18:42:21 +000040using android::base::Result;
41
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080042/**
43 * Log debug messages relating to the consumer end of the transport channel.
44 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
45 */
46const bool DEBUG_TRANSPORT_CONSUMER =
47 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
48
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070049std::unique_ptr<KeyEvent> createKeyEvent(const InputMessage& msg) {
50 std::unique_ptr<KeyEvent> event = std::make_unique<KeyEvent>();
51 event->initialize(msg.body.key.eventId, msg.body.key.deviceId, msg.body.key.source,
Linnan Li13bf76a2024-05-05 19:18:02 +080052 ui::LogicalDisplayId{msg.body.key.displayId}, msg.body.key.hmac,
53 msg.body.key.action, msg.body.key.flags, msg.body.key.keyCode,
54 msg.body.key.scanCode, msg.body.key.metaState, msg.body.key.repeatCount,
55 msg.body.key.downTime, msg.body.key.eventTime);
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070056 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080057}
58
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070059std::unique_ptr<FocusEvent> createFocusEvent(const InputMessage& msg) {
60 std::unique_ptr<FocusEvent> event = std::make_unique<FocusEvent>();
61 event->initialize(msg.body.focus.eventId, msg.body.focus.hasFocus);
62 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080063}
64
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070065std::unique_ptr<CaptureEvent> createCaptureEvent(const InputMessage& msg) {
66 std::unique_ptr<CaptureEvent> event = std::make_unique<CaptureEvent>();
67 event->initialize(msg.body.capture.eventId, msg.body.capture.pointerCaptureEnabled);
68 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080069}
70
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070071std::unique_ptr<DragEvent> createDragEvent(const InputMessage& msg) {
72 std::unique_ptr<DragEvent> event = std::make_unique<DragEvent>();
73 event->initialize(msg.body.drag.eventId, msg.body.drag.x, msg.body.drag.y,
74 msg.body.drag.isExiting);
75 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080076}
77
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070078std::unique_ptr<MotionEvent> createMotionEvent(const InputMessage& msg) {
79 std::unique_ptr<MotionEvent> event = std::make_unique<MotionEvent>();
Siarhei Vishniakou2b920272024-02-27 19:49:51 -080080 const uint32_t pointerCount = msg.body.motion.pointerCount;
81 std::vector<PointerProperties> pointerProperties;
82 pointerProperties.reserve(pointerCount);
83 std::vector<PointerCoords> pointerCoords;
84 pointerCoords.reserve(pointerCount);
85 for (uint32_t i = 0; i < pointerCount; i++) {
86 pointerProperties.push_back(msg.body.motion.pointers[i].properties);
87 pointerCoords.push_back(msg.body.motion.pointers[i].coords);
88 }
89
90 ui::Transform transform;
91 transform.set({msg.body.motion.dsdx, msg.body.motion.dtdx, msg.body.motion.tx,
92 msg.body.motion.dtdy, msg.body.motion.dsdy, msg.body.motion.ty, 0, 0, 1});
93 ui::Transform displayTransform;
94 displayTransform.set({msg.body.motion.dsdxRaw, msg.body.motion.dtdxRaw, msg.body.motion.txRaw,
95 msg.body.motion.dtdyRaw, msg.body.motion.dsdyRaw, msg.body.motion.tyRaw,
96 0, 0, 1});
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -070097 event->initialize(msg.body.motion.eventId, msg.body.motion.deviceId, msg.body.motion.source,
Linnan Li13bf76a2024-05-05 19:18:02 +080098 ui::LogicalDisplayId{msg.body.motion.displayId}, msg.body.motion.hmac,
99 msg.body.motion.action, msg.body.motion.actionButton, msg.body.motion.flags,
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700100 msg.body.motion.edgeFlags, msg.body.motion.metaState,
101 msg.body.motion.buttonState, msg.body.motion.classification, transform,
102 msg.body.motion.xPrecision, msg.body.motion.yPrecision,
103 msg.body.motion.xCursorPosition, msg.body.motion.yCursorPosition,
104 displayTransform, msg.body.motion.downTime, msg.body.motion.eventTime,
105 pointerCount, pointerProperties.data(), pointerCoords.data());
106 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800107}
108
109void addSample(MotionEvent& event, const InputMessage& msg) {
110 uint32_t pointerCount = msg.body.motion.pointerCount;
111 std::vector<PointerCoords> pointerCoords;
112 pointerCoords.reserve(pointerCount);
113 for (uint32_t i = 0; i < pointerCount; i++) {
114 pointerCoords.push_back(msg.body.motion.pointers[i].coords);
115 }
116
117 // TODO(b/329770983): figure out if it's safe to combine events with mismatching metaState
118 event.setMetaState(event.getMetaState() | msg.body.motion.metaState);
jioana71c6f732024-07-16 15:42:56 +0000119 event.addSample(msg.body.motion.eventTime, pointerCoords.data(), msg.body.motion.eventId);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800120}
121
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700122std::unique_ptr<TouchModeEvent> createTouchModeEvent(const InputMessage& msg) {
123 std::unique_ptr<TouchModeEvent> event = std::make_unique<TouchModeEvent>();
124 event->initialize(msg.body.touchMode.eventId, msg.body.touchMode.isInTouchMode);
125 return event;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800126}
127
128std::string outboundMessageToString(const InputMessage& outboundMsg) {
129 switch (outboundMsg.header.type) {
130 case InputMessage::Type::FINISHED: {
131 return android::base::StringPrintf(" Finish: seq=%" PRIu32 " handled=%s",
132 outboundMsg.header.seq,
133 toString(outboundMsg.body.finished.handled));
134 }
135 case InputMessage::Type::TIMELINE: {
136 return android::base::
137 StringPrintf(" Timeline: inputEventId=%" PRId32 " gpuCompletedTime=%" PRId64
138 ", presentTime=%" PRId64,
139 outboundMsg.body.timeline.eventId,
140 outboundMsg.body.timeline
141 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
142 outboundMsg.body.timeline
143 .graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
144 }
145 default: {
146 LOG(FATAL) << "Outbound message must be FINISHED or TIMELINE, got "
147 << ftl::enum_string(outboundMsg.header.type);
148 return "Unreachable";
149 }
150 }
151}
152
153InputMessage createFinishedMessage(uint32_t seq, bool handled, nsecs_t consumeTime) {
154 InputMessage msg;
155 msg.header.type = InputMessage::Type::FINISHED;
156 msg.header.seq = seq;
157 msg.body.finished.handled = handled;
158 msg.body.finished.consumeTime = consumeTime;
159 return msg;
160}
161
162InputMessage createTimelineMessage(int32_t inputEventId, nsecs_t gpuCompletedTime,
163 nsecs_t presentTime) {
164 InputMessage msg;
165 msg.header.type = InputMessage::Type::TIMELINE;
166 msg.header.seq = 0;
167 msg.body.timeline.eventId = inputEventId;
168 msg.body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = gpuCompletedTime;
169 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = presentTime;
170 return msg;
171}
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800172} // namespace
173
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800174// --- InputConsumerNoResampling ---
175
Paul Ramireze37f8342024-08-28 18:42:21 +0000176InputConsumerNoResampling::InputConsumerNoResampling(
177 const std::shared_ptr<InputChannel>& channel, sp<Looper> looper,
178 InputConsumerCallbacks& callbacks,
179 std::function<std::unique_ptr<Resampler>()> resamplerCreator)
Paul Ramireze2bb1872024-08-12 20:21:13 +0000180 : mChannel{channel},
181 mLooper{looper},
Paul Ramirez87f1c012024-09-18 18:23:14 +0000182 mCallbacks{callbacks},
Paul Ramireze37f8342024-08-28 18:42:21 +0000183 mResamplerCreator{std::move(resamplerCreator)},
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000184 mFdEvents(0) {
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800185 LOG_ALWAYS_FATAL_IF(mLooper == nullptr);
186 mCallback = sp<LooperEventCallback>::make(
187 std::bind(&InputConsumerNoResampling::handleReceiveCallback, this,
188 std::placeholders::_1));
189 // In the beginning, there are no pending outbounds events; we only care about receiving
190 // incoming data.
191 setFdEvents(ALOOPER_EVENT_INPUT);
192}
193
194InputConsumerNoResampling::~InputConsumerNoResampling() {
195 ensureCalledOnLooperThread(__func__);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800196 while (!mOutboundQueue.empty()) {
197 processOutboundEvents();
198 // This is our last chance to ack the events. If we don't ack them here, we will get an ANR,
199 // so keep trying to send the events as long as they are present in the queue.
200 }
Siarhei Vishniakoubc723092024-10-08 15:41:51 -0700201
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800202 setFdEvents(0);
Siarhei Vishniakoubc723092024-10-08 15:41:51 -0700203 // If there are any remaining unread batches, send an ack for them and don't deliver
204 // them to callbacks.
205 for (auto& [_, batches] : mBatches) {
206 while (!batches.empty()) {
207 finishInputEvent(batches.front().header.seq, /*handled=*/false);
208 batches.pop();
209 }
210 }
211 // However, it is still up to the app to finish any events that have already been delivered
212 // to the callbacks. If we wanted to change that behaviour and auto-finish all unfinished events
213 // that were already sent to callbacks, we could potentially loop through "mConsumeTimes"
214 // instead. We can't use "mBatchedSequenceNumbers" for this purpose, because it only contains
215 // batchable (i.e., ACTION_MOVE) events that were sent to the callbacks.
216 const size_t unfinishedEvents = mConsumeTimes.size();
217 LOG_IF(INFO, unfinishedEvents != 0)
218 << getName() << " has " << unfinishedEvents << " unfinished event(s)";
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800219}
220
221int InputConsumerNoResampling::handleReceiveCallback(int events) {
222 // Allowed return values of this function as documented in LooperCallback::handleEvent
223 constexpr int REMOVE_CALLBACK = 0;
224 constexpr int KEEP_CALLBACK = 1;
225
226 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
227 // This error typically occurs when the publisher has closed the input channel
228 // as part of removing a window or finishing an IME session, in which case
229 // the consumer will soon be disposed as well.
230 if (DEBUG_TRANSPORT_CONSUMER) {
231 LOG(INFO) << "The channel was hung up or an error occurred: " << mChannel->getName();
232 }
233 return REMOVE_CALLBACK;
234 }
235
236 int handledEvents = 0;
237 if (events & ALOOPER_EVENT_INPUT) {
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000238 handleMessages(readAllMessages());
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800239 handledEvents |= ALOOPER_EVENT_INPUT;
240 }
241
242 if (events & ALOOPER_EVENT_OUTPUT) {
243 processOutboundEvents();
244 handledEvents |= ALOOPER_EVENT_OUTPUT;
245 }
246 if (handledEvents != events) {
247 LOG(FATAL) << "Mismatch: handledEvents=" << handledEvents << ", events=" << events;
248 }
249 return KEEP_CALLBACK;
250}
251
252void InputConsumerNoResampling::processOutboundEvents() {
253 while (!mOutboundQueue.empty()) {
254 const InputMessage& outboundMsg = mOutboundQueue.front();
255
256 const status_t result = mChannel->sendMessage(&outboundMsg);
257 if (result == OK) {
258 if (outboundMsg.header.type == InputMessage::Type::FINISHED) {
259 ATRACE_ASYNC_END("InputConsumer processing", /*cookie=*/outboundMsg.header.seq);
260 }
261 // Successful send. Erase the entry and keep trying to send more
262 mOutboundQueue.pop();
263 continue;
264 }
265
266 // Publisher is busy, try again later. Keep this entry (do not erase)
267 if (result == WOULD_BLOCK) {
268 setFdEvents(ALOOPER_EVENT_INPUT | ALOOPER_EVENT_OUTPUT);
269 return; // try again later
270 }
271
272 // Some other error. Give up
273 LOG(FATAL) << "Failed to send outbound event on channel '" << mChannel->getName()
274 << "'. status=" << statusToString(result) << "(" << result << ")";
275 }
276
277 // The queue is now empty. Tell looper there's no more output to expect.
278 setFdEvents(ALOOPER_EVENT_INPUT);
279}
280
281void InputConsumerNoResampling::finishInputEvent(uint32_t seq, bool handled) {
282 ensureCalledOnLooperThread(__func__);
283 mOutboundQueue.push(createFinishedMessage(seq, handled, popConsumeTime(seq)));
284 // also produce finish events for all batches for this seq (if any)
285 const auto it = mBatchedSequenceNumbers.find(seq);
286 if (it != mBatchedSequenceNumbers.end()) {
287 for (uint32_t subSeq : it->second) {
288 mOutboundQueue.push(createFinishedMessage(subSeq, handled, popConsumeTime(subSeq)));
289 }
290 mBatchedSequenceNumbers.erase(it);
291 }
292 processOutboundEvents();
293}
294
295bool InputConsumerNoResampling::probablyHasInput() const {
296 // Ideally, this would only be allowed to run on the looper thread, and in production, it will.
297 // However, for testing, it's convenient to call this while the looper thread is blocked, so
298 // we do not call ensureCalledOnLooperThread here.
299 return (!mBatches.empty()) || mChannel->probablyHasInput();
300}
301
302void InputConsumerNoResampling::reportTimeline(int32_t inputEventId, nsecs_t gpuCompletedTime,
303 nsecs_t presentTime) {
304 ensureCalledOnLooperThread(__func__);
305 mOutboundQueue.push(createTimelineMessage(inputEventId, gpuCompletedTime, presentTime));
306 processOutboundEvents();
307}
308
309nsecs_t InputConsumerNoResampling::popConsumeTime(uint32_t seq) {
310 auto it = mConsumeTimes.find(seq);
311 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
312 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
313 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
314 seq);
315 nsecs_t consumeTime = it->second;
316 mConsumeTimes.erase(it);
317 return consumeTime;
318}
319
320void InputConsumerNoResampling::setFdEvents(int events) {
321 if (mFdEvents != events) {
322 mFdEvents = events;
323 if (events != 0) {
324 mLooper->addFd(mChannel->getFd(), 0, events, mCallback, nullptr);
325 } else {
326 mLooper->removeFd(mChannel->getFd());
327 }
328 }
329}
330
331void InputConsumerNoResampling::handleMessages(std::vector<InputMessage>&& messages) {
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800332 for (const InputMessage& msg : messages) {
333 if (msg.header.type == InputMessage::Type::MOTION) {
334 const int32_t action = msg.body.motion.action;
335 const DeviceId deviceId = msg.body.motion.deviceId;
336 const int32_t source = msg.body.motion.source;
337 const bool batchableEvent = (action == AMOTION_EVENT_ACTION_MOVE ||
338 action == AMOTION_EVENT_ACTION_HOVER_MOVE) &&
339 (isFromSource(source, AINPUT_SOURCE_CLASS_POINTER) ||
340 isFromSource(source, AINPUT_SOURCE_CLASS_JOYSTICK));
Paul Ramireze37f8342024-08-28 18:42:21 +0000341
342 const bool canResample = (mResamplerCreator != nullptr) &&
343 (isFromSource(source, AINPUT_SOURCE_CLASS_POINTER));
344 if (canResample) {
345 if (action == AMOTION_EVENT_ACTION_DOWN) {
346 if (std::unique_ptr<Resampler> resampler = mResamplerCreator();
347 resampler != nullptr) {
348 const auto [_, inserted] =
349 mResamplers.insert(std::pair(deviceId, std::move(resampler)));
350 LOG_IF(WARNING, !inserted) << deviceId << "already exists in mResamplers";
351 }
352 }
353 }
354
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800355 if (batchableEvent) {
356 // add it to batch
357 mBatches[deviceId].emplace(msg);
358 } else {
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000359 // consume all pending batches for this device immediately
Paul Ramirez37242c82024-10-18 23:16:43 +0000360 consumeBatchedInputEvents(deviceId, /*requestedFrameTime=*/
361 std::numeric_limits<nsecs_t>::max());
Paul Ramireze37f8342024-08-28 18:42:21 +0000362 if (canResample &&
363 (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL)) {
364 LOG_IF(INFO, mResamplers.erase(deviceId) == 0)
365 << deviceId << "does not exist in mResamplers";
366 }
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800367 handleMessage(msg);
368 }
369 } else {
370 // Non-motion events shouldn't force the consumption of pending batched events
371 handleMessage(msg);
372 }
373 }
374 // At the end of this, if we still have pending batches, notify the receiver about it.
375
376 // We need to carefully notify the InputConsumerCallbacks about the pending batch. The receiver
377 // could choose to consume all events when notified about the batch. That means that the
378 // "mBatches" variable could change when 'InputConsumerCallbacks::onBatchedInputEventPending' is
379 // invoked. We also can't notify the InputConsumerCallbacks in a while loop until mBatches is
380 // empty, because the receiver could choose to not consume the batch immediately.
381 std::set<int32_t> pendingBatchSources;
382 for (const auto& [_, pendingMessages] : mBatches) {
383 // Assume that all messages for a given device has the same source.
384 pendingBatchSources.insert(pendingMessages.front().body.motion.source);
385 }
386 for (const int32_t source : pendingBatchSources) {
387 const bool sourceStillRemaining =
388 std::any_of(mBatches.begin(), mBatches.end(), [=](const auto& pair) {
389 return pair.second.front().body.motion.source == source;
390 });
391 if (sourceStillRemaining) {
392 mCallbacks.onBatchedInputEventPending(source);
393 }
394 }
395}
396
397std::vector<InputMessage> InputConsumerNoResampling::readAllMessages() {
398 std::vector<InputMessage> messages;
399 while (true) {
Paul Ramirez0c25e862024-06-18 21:33:33 +0000400 android::base::Result<InputMessage> result = mChannel->receiveMessage();
401 if (result.ok()) {
402 const InputMessage& msg = *result;
403 const auto [_, inserted] =
404 mConsumeTimes.emplace(msg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
405 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
406 msg.header.seq);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800407
Paul Ramirez0c25e862024-06-18 21:33:33 +0000408 // Trace the event processing timeline - event was just read from the socket
409 // TODO(b/329777420): distinguish between multiple instances of InputConsumer
410 // in the same process.
411 ATRACE_ASYNC_BEGIN("InputConsumer processing", /*cookie=*/msg.header.seq);
412 messages.push_back(msg);
413 } else { // !result.ok()
414 switch (result.error().code()) {
415 case WOULD_BLOCK: {
416 return messages;
417 }
418 case DEAD_OBJECT: {
419 LOG(FATAL) << "Got a dead object for " << mChannel->getName();
420 break;
421 }
422 case BAD_VALUE: {
423 LOG(FATAL) << "Got a bad value for " << mChannel->getName();
424 break;
425 }
426 default: {
427 LOG(FATAL) << "Unexpected error: " << result.error().message();
428 break;
429 }
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800430 }
431 }
432 }
433}
434
435void InputConsumerNoResampling::handleMessage(const InputMessage& msg) const {
436 switch (msg.header.type) {
437 case InputMessage::Type::KEY: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700438 std::unique_ptr<KeyEvent> keyEvent = createKeyEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800439 mCallbacks.onKeyEvent(std::move(keyEvent), msg.header.seq);
440 break;
441 }
442
443 case InputMessage::Type::MOTION: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700444 std::unique_ptr<MotionEvent> motionEvent = createMotionEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800445 mCallbacks.onMotionEvent(std::move(motionEvent), msg.header.seq);
446 break;
447 }
448
449 case InputMessage::Type::FINISHED:
450 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou11d223b2024-03-26 21:52:38 +0000451 LOG(FATAL) << "Consumed a " << ftl::enum_string(msg.header.type)
452 << " message, which should never be seen by InputConsumer on "
453 << mChannel->getName();
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800454 break;
455 }
456
457 case InputMessage::Type::FOCUS: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700458 std::unique_ptr<FocusEvent> focusEvent = createFocusEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800459 mCallbacks.onFocusEvent(std::move(focusEvent), msg.header.seq);
460 break;
461 }
462
463 case InputMessage::Type::CAPTURE: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700464 std::unique_ptr<CaptureEvent> captureEvent = createCaptureEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800465 mCallbacks.onCaptureEvent(std::move(captureEvent), msg.header.seq);
466 break;
467 }
468
469 case InputMessage::Type::DRAG: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700470 std::unique_ptr<DragEvent> dragEvent = createDragEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800471 mCallbacks.onDragEvent(std::move(dragEvent), msg.header.seq);
472 break;
473 }
474
475 case InputMessage::Type::TOUCH_MODE: {
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700476 std::unique_ptr<TouchModeEvent> touchModeEvent = createTouchModeEvent(msg);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800477 mCallbacks.onTouchModeEvent(std::move(touchModeEvent), msg.header.seq);
478 break;
479 }
480 }
481}
482
Paul Ramirezb41d38e2024-07-16 17:44:20 +0000483std::pair<std::unique_ptr<MotionEvent>, std::optional<uint32_t>>
Paul Ramirez37242c82024-10-18 23:16:43 +0000484InputConsumerNoResampling::createBatchedMotionEvent(const std::optional<nsecs_t> requestedFrameTime,
Paul Ramirezb41d38e2024-07-16 17:44:20 +0000485 std::queue<InputMessage>& messages) {
486 std::unique_ptr<MotionEvent> motionEvent;
487 std::optional<uint32_t> firstSeqForBatch;
Paul Ramireze37f8342024-08-28 18:42:21 +0000488
489 LOG_IF(FATAL, messages.empty()) << "messages queue is empty!";
490 const DeviceId deviceId = messages.front().body.motion.deviceId;
491 const auto resampler = mResamplers.find(deviceId);
492 const nanoseconds resampleLatency = (resampler != mResamplers.cend())
493 ? resampler->second->getResampleLatency()
494 : nanoseconds{0};
Paul Ramirez37242c82024-10-18 23:16:43 +0000495 // When batching is not enabled, we want to consume all events. That's equivalent to having an
496 // infinite requestedFrameTime.
497 const nanoseconds adjustedFrameTime = (requestedFrameTime.has_value())
498 ? (nanoseconds{*requestedFrameTime} - resampleLatency)
499 : nanoseconds{std::numeric_limits<nsecs_t>::max()};
Paul Ramirezcd7488c2024-09-13 23:01:12 +0000500
501 while (!messages.empty() &&
502 (messages.front().body.motion.eventTime <= adjustedFrameTime.count())) {
Paul Ramirezb41d38e2024-07-16 17:44:20 +0000503 if (motionEvent == nullptr) {
504 motionEvent = createMotionEvent(messages.front());
505 firstSeqForBatch = messages.front().header.seq;
506 const auto [_, inserted] = mBatchedSequenceNumbers.insert({*firstSeqForBatch, {}});
507 LOG_IF(FATAL, !inserted)
508 << "The sequence " << messages.front().header.seq << " was already present!";
509 } else {
510 addSample(*motionEvent, messages.front());
511 mBatchedSequenceNumbers[*firstSeqForBatch].push_back(messages.front().header.seq);
512 }
513 messages.pop();
514 }
Paul Ramireze37f8342024-08-28 18:42:21 +0000515
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000516 // Check if resampling should be performed.
Paul Ramireze37f8342024-08-28 18:42:21 +0000517 InputMessage* futureSample = nullptr;
518 if (!messages.empty()) {
519 futureSample = &messages.front();
Paul Ramirezbe9c5442024-07-10 00:12:41 +0000520 }
Paul Ramirez37242c82024-10-18 23:16:43 +0000521 if ((motionEvent != nullptr) && (resampler != mResamplers.cend()) &&
522 (requestedFrameTime.has_value())) {
523 resampler->second->resampleMotionEvent(nanoseconds{*requestedFrameTime}, *motionEvent,
Paul Ramireze37f8342024-08-28 18:42:21 +0000524 futureSample);
525 }
526
Paul Ramirezb41d38e2024-07-16 17:44:20 +0000527 return std::make_pair(std::move(motionEvent), firstSeqForBatch);
528}
529
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800530bool InputConsumerNoResampling::consumeBatchedInputEvents(
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000531 std::optional<DeviceId> deviceId, std::optional<nsecs_t> requestedFrameTime) {
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800532 ensureCalledOnLooperThread(__func__);
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800533 bool producedEvents = false;
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000534
535 for (auto deviceIdIter = (deviceId.has_value()) ? (mBatches.find(*deviceId))
536 : (mBatches.begin());
537 deviceIdIter != mBatches.cend(); ++deviceIdIter) {
538 std::queue<InputMessage>& messages = deviceIdIter->second;
Paul Ramirez37242c82024-10-18 23:16:43 +0000539 auto [motion, firstSeqForBatch] = createBatchedMotionEvent(requestedFrameTime, messages);
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700540 if (motion != nullptr) {
541 LOG_ALWAYS_FATAL_IF(!firstSeqForBatch.has_value());
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800542 mCallbacks.onMotionEvent(std::move(motion), *firstSeqForBatch);
543 producedEvents = true;
544 } else {
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000545 // This is OK, it just means that the requestedFrameTime is too old (all events that we
546 // have pending are in the future of the requestedFrameTime). Maybe print a warning? If
547 // there are multiple devices active though, this might be normal and can just be
548 // ignored, unless none of them resulted in any consumption (in that case, this function
549 // would already return "false" so we could just leave it up to the caller).
550 }
551
552 if (deviceId.has_value()) {
553 // We already consumed events for this device. Break here to prevent iterating over the
554 // other devices.
555 break;
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800556 }
557 }
558 std::erase_if(mBatches, [](const auto& pair) { return pair.second.empty(); });
559 return producedEvents;
560}
561
Paul Ramirez00cf5d02024-09-05 17:10:12 +0000562bool InputConsumerNoResampling::consumeBatchedInputEvents(
563 std::optional<nsecs_t> requestedFrameTime) {
564 return consumeBatchedInputEvents(/*deviceId=*/std::nullopt, requestedFrameTime);
565}
566
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800567void InputConsumerNoResampling::ensureCalledOnLooperThread(const char* func) const {
568 sp<Looper> callingThreadLooper = Looper::getForThread();
Paul Ramirez87f1c012024-09-18 18:23:14 +0000569 if (callingThreadLooper != mLooper) {
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800570 LOG(FATAL) << "The function " << func << " can only be called on the looper thread";
571 }
572}
573
574std::string InputConsumerNoResampling::dump() const {
575 ensureCalledOnLooperThread(__func__);
576 std::string out;
577 if (mOutboundQueue.empty()) {
578 out += "mOutboundQueue: <empty>\n";
579 } else {
580 out += "mOutboundQueue:\n";
581 // Make a copy of mOutboundQueue for printing destructively. Unfortunately std::queue
582 // doesn't provide a good way to iterate over the entire container.
583 std::queue<InputMessage> tmpQueue = mOutboundQueue;
584 while (!tmpQueue.empty()) {
585 out += std::string(" ") + outboundMessageToString(tmpQueue.front()) + "\n";
586 tmpQueue.pop();
587 }
588 }
589
590 if (mBatches.empty()) {
591 out += "mBatches: <empty>\n";
592 } else {
593 out += "mBatches:\n";
594 for (const auto& [deviceId, messages] : mBatches) {
595 out += " Device id ";
596 out += std::to_string(deviceId);
597 out += ":\n";
598 // Make a copy of mOutboundQueue for printing destructively. Unfortunately std::queue
599 // doesn't provide a good way to iterate over the entire container.
600 std::queue<InputMessage> tmpQueue = messages;
601 while (!tmpQueue.empty()) {
602 LOG_ALWAYS_FATAL_IF(tmpQueue.front().header.type != InputMessage::Type::MOTION);
Siarhei Vishniakou3891ec92024-03-15 13:29:57 -0700603 std::unique_ptr<MotionEvent> motion = createMotionEvent(tmpQueue.front());
604 out += std::string(" ") + streamableToString(*motion) + "\n";
Siarhei Vishniakou2b920272024-02-27 19:49:51 -0800605 tmpQueue.pop();
606 }
607 }
608 }
609
610 return out;
611}
612
613} // namespace android