| /* | |
| * Copyright 2026 The Android Open Source Project | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| #define LOG_TAG "InputJankTracker" | |
| #define ATRACE_TAG ATRACE_TAG_INPUT | |
| #include <input/InputJankTracker.h> | |
| #include <algorithm> | |
| #include <format> | |
| #include <android-base/logging.h> | |
| #include <input/TraceTools.h> | |
| namespace input_flags = com::android::input::flags; | |
| namespace android { | |
| namespace { | |
| /** | |
| * Log debug messages relating to input jank tracking. | |
| * Enable this via "adb shell setprop log.tag.InputJankTracker DEBUG" | |
| */ | |
| const bool DEBUG_INPUT_JANK_TRACKER = | |
| __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO); | |
| constexpr size_t MAX_PENDING_FRAMES = 300; | |
| } // namespace | |
| // --- InputJankTracker --- | |
| InputJankTracker::InputJankTracker(const std::string& logTag) : mLogTag(logTag) {} | |
| InputJankTracker::DeviceStats& InputJankTracker::getOrCreateDeviceStats(int32_t deviceId) { | |
| auto [it, inserted] = mDeviceStats.try_emplace(deviceId, deviceId); | |
| return it->second; | |
| } | |
| void InputJankTracker::processConsumedMotion(const InputMessage::Body::Motion& motion) { | |
| if (!input_flags::enable_input_jank_tracker()) return; | |
| if (motion.eventTime <= 0) return; | |
| if (!isFromSource(motion.source, AINPUT_SOURCE_CLASS_POINTER)) return; | |
| int32_t action = motion.action & AMOTION_EVENT_ACTION_MASK; | |
| InputDeviceUsageSource usageSource = getUsageSourceForMotion(motion); | |
| if (action == AMOTION_EVENT_ACTION_DOWN) { | |
| onGestureStart(motion.deviceId, usageSource, motion.eventTime); | |
| } | |
| onEventConsumed(motion.deviceId, usageSource, motion.eventId, motion.action, motion.eventTime); | |
| if (action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_CANCEL) { | |
| onGestureEnd(motion.deviceId, motion.eventTime); | |
| } | |
| } | |
| void InputJankTracker::onGestureStart(int32_t deviceId, InputDeviceUsageSource inputSource, | |
| nsecs_t startTime) { | |
| auto it = mActiveGestures.find(deviceId); | |
| if (it != mActiveGestures.end()) { | |
| LOG(ERROR) << std::format("Received gesture start for device {} while a " | |
| "previous gesture was still active ({})", | |
| deviceId, mLogTag); | |
| it->second.onGestureEnd(it->second.getCurrentFrameTime(), mLogTag, | |
| /*byref*/ getOrCreateDeviceStats(deviceId)); | |
| mActiveGestures.erase(it); | |
| } | |
| mActiveGestures.emplace(std::piecewise_construct, std::forward_as_tuple(deviceId), | |
| std::forward_as_tuple(inputSource, mLogTag)); | |
| onNewFrame(startTime); | |
| } | |
| void InputJankTracker::onGestureEnd(int32_t deviceId, nsecs_t endTime) { | |
| auto it = mActiveGestures.find(deviceId); | |
| if (it != mActiveGestures.end()) { | |
| it->second.onGestureEnd(endTime, mLogTag, /*byref*/ getOrCreateDeviceStats(deviceId)); | |
| mActiveGestures.erase(it); | |
| } | |
| } | |
| void InputJankTracker::onNewFrame(nsecs_t requestedFrameTime) { | |
| if (!input_flags::enable_input_jank_tracker()) return; | |
| if (requestedFrameTime < 0) return; | |
| for (auto& [deviceId, tracker] : mActiveGestures) { | |
| tracker.onNewFrame(requestedFrameTime, /*byref*/ getOrCreateDeviceStats(deviceId)); | |
| } | |
| } | |
| void InputJankTracker::onEventConsumed(int32_t deviceId, InputDeviceUsageSource inputSource, | |
| int32_t id, int32_t action, nsecs_t eventTime) { | |
| auto it = mActiveGestures.find(deviceId); | |
| if (it != mActiveGestures.end()) { | |
| if (inputSource == it->second.getSource()) { | |
| it->second.onEventConsumed(id, action, eventTime); | |
| } | |
| } | |
| } | |
| // --- InputJankTracker::DeviceStats --- | |
| void InputJankTracker::DeviceStats::updateAndReport(size_t gestureJankCount, | |
| size_t gestureTotalCount, | |
| const std::string& logTag) { | |
| if (gestureTotalCount == 0) return; | |
| mOverallJankCount += gestureJankCount; | |
| mOverallTotalCount += gestureTotalCount; | |
| float gestureRate = static_cast<float>(gestureJankCount) / gestureTotalCount * 100.0f; | |
| float overallRate = static_cast<float>(mOverallJankCount) / mOverallTotalCount * 100.0f; | |
| std::string msg = | |
| std::format("Input Jank Detection ({}): Gesture ended for device {}. " | |
| "Last Frame Jank: {}/{}. Gesture Jank rate: {}/{} ({:.1f}%). " | |
| "Device {} Overall Jank rate: {}/{} ({:.1f}%)", | |
| logTag, mDeviceId, mLastFrameTelemetry.jankFrameCount, | |
| mLastFrameTelemetry.totalFrameCount, gestureJankCount, | |
| gestureTotalCount, gestureRate, mDeviceId, mOverallJankCount, | |
| mOverallTotalCount, overallRate); | |
| if (gestureJankCount > 0) { | |
| LOG(WARNING) << msg; | |
| } else { | |
| LOG_IF(INFO, DEBUG_INPUT_JANK_TRACKER) << msg; | |
| } | |
| } | |
| // --- InputJankTracker::GestureTracker --- | |
| InputJankTracker::GestureTracker::GestureTracker(InputDeviceUsageSource source, | |
| const std::string& logTag) | |
| : mSource(source), mLogTag(logTag), mCurrentFrameTime(-1), mLastFrameTime(-1) {} | |
| void InputJankTracker::GestureTracker::onNewFrame(nsecs_t requestedFrameTime, | |
| DeviceStats& deviceStats) { | |
| if (requestedFrameTime <= mCurrentFrameTime) return; | |
| mLatestEvaluatedTelemetry.reset(); | |
| if (mCurrentFrameTime >= 0) { | |
| evaluateFrameJank(mCurrentFrameTime, /*isGestureEnd=*/false, /*byref*/ deviceStats); | |
| } | |
| mLastFrameTime = mCurrentFrameTime; | |
| mCurrentFrameTime = requestedFrameTime; | |
| } | |
| static std::string actionToString(int32_t action) { | |
| int32_t masked = action & AMOTION_EVENT_ACTION_MASK; | |
| switch (masked) { | |
| case AMOTION_EVENT_ACTION_DOWN: | |
| return "DOWN(0x0)"; | |
| case AMOTION_EVENT_ACTION_UP: | |
| return "UP(0x1)"; | |
| case AMOTION_EVENT_ACTION_MOVE: | |
| return "MOVE(0x2)"; | |
| case AMOTION_EVENT_ACTION_CANCEL: | |
| return "CANCEL(0x3)"; | |
| case AMOTION_EVENT_ACTION_POINTER_DOWN: { | |
| int32_t idx = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> | |
| AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; | |
| return "POINTER_DOWN(0x5,ptr=" + std::to_string(idx) + ")"; | |
| } | |
| case AMOTION_EVENT_ACTION_POINTER_UP: { | |
| int32_t idx = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> | |
| AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; | |
| return "POINTER_UP(0x6,ptr=" + std::to_string(idx) + ")"; | |
| } | |
| default: | |
| return "ACTION(0x" + std::to_string(masked) + ")"; | |
| } | |
| } | |
| void InputJankTracker::GestureTracker::onEventConsumed(int32_t id, int32_t action, | |
| nsecs_t eventTime) { | |
| if ((action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_DOWN) { | |
| return; | |
| } | |
| if (mCurrentFrameTime >= 0 && eventTime > mCurrentFrameTime) { | |
| LOG_IF(WARNING, DEBUG_INPUT_JANK_TRACKER) | |
| << std::format("Ignoring event {} with eventTime {} which is newer " | |
| "than current frameTime {}", | |
| id, eventTime, mCurrentFrameTime); | |
| return; | |
| } | |
| mConsumedEvents.push_back({.id = id, .eventTime = eventTime, .action = action}); | |
| } | |
| void InputJankTracker::GestureTracker::onGestureEnd(nsecs_t endTime, | |
| const std::string& logTag, | |
| DeviceStats& deviceStats) { | |
| nsecs_t endFrameTime = std::max(endTime, mCurrentFrameTime); | |
| evaluateFrameJank(endFrameTime, /*isGestureEnd=*/true, /*byref*/ deviceStats); | |
| deviceStats.updateAndReport(mAccumulatedJankCount, mAccumulatedTotalCount, logTag); | |
| } | |
| void InputJankTracker::GestureTracker::mapEventsToPendingFrames() { | |
| ssize_t frameIndex = static_cast<ssize_t>(mPendingFrames.size()) - 1; | |
| ssize_t eventIndex = static_cast<ssize_t>(mConsumedEvents.size()) - 1; | |
| while (eventIndex >= 0 && frameIndex >= 0) { | |
| nsecs_t eventTime = mConsumedEvents[eventIndex].eventTime; | |
| FrameRecord& frame = mPendingFrames[frameIndex]; | |
| if (eventTime >= frame.start && eventTime <= frame.end) { | |
| frame.expectedCount++; | |
| eventIndex--; | |
| } else if (eventTime < frame.start) { | |
| frameIndex--; | |
| } else { | |
| eventIndex--; | |
| } | |
| } | |
| } | |
| InputJankTracker::GestureTracker::JankEvaluationResult | |
| InputJankTracker::GestureTracker::determineJank(bool isGestureEnd) { | |
| JankEvaluationResult result; | |
| nsecs_t lastEventTime = mConsumedEvents.back().eventTime; | |
| for (size_t i = 0; i < mPendingFrames.size(); i++) { | |
| auto& frame = mPendingFrames[i]; | |
| bool shouldDefer = false; | |
| if (frame.consumedCount == 0) { | |
| if (frame.expectedCount == 0) { | |
| shouldDefer = lastEventTime < frame.start; | |
| } else { | |
| result.jankCount++; | |
| result.totalCount++; | |
| } | |
| } else { | |
| if (frame.expectedCount > 0) { | |
| result.totalCount++; | |
| } else if (!isGestureEnd) { | |
| shouldDefer = true; | |
| frame.consumedCount = 0; | |
| } | |
| } | |
| if (shouldDefer) { | |
| result.remainingFrames.push_back(frame); | |
| } | |
| } | |
| return result; | |
| } | |
| void InputJankTracker::GestureTracker::updateTelemetry(size_t totalCount, size_t jankCount, | |
| DeviceStats& deviceStats) { | |
| mAccumulatedJankCount += jankCount; | |
| mAccumulatedTotalCount += totalCount; | |
| JankFrameTelemetry telemetry; | |
| if (!mConsumedEvents.empty()) { | |
| telemetry.oldestInputEventId = mConsumedEvents.front().id; | |
| telemetry.oldestInputEventTimestamp = mConsumedEvents.front().eventTime; | |
| telemetry.latestInputEventId = mConsumedEvents.back().id; | |
| telemetry.latestInputEventTimestamp = mConsumedEvents.back().eventTime; | |
| telemetry.consumedInputEventCount = static_cast<int32_t>(mConsumedEvents.size()); | |
| } | |
| telemetry.totalFrameCount = static_cast<int32_t>(totalCount); | |
| telemetry.jankFrameCount = static_cast<int32_t>(jankCount); | |
| telemetry.inputSource = static_cast<int32_t>(mSource); | |
| deviceStats.setLastFrameTelemetry(telemetry); | |
| mLatestEvaluatedTelemetry = telemetry; | |
| } | |
| void InputJankTracker::GestureTracker::logJank(nsecs_t frameTime, size_t jankCount, | |
| size_t totalCount) const { | |
| LOG(WARNING) << std::format("Input Jank Detected [frameTime:{}] ({}): Processed {} " | |
| "frame(s), detected {} jank frame(s). Current gesture " | |
| "jank: {}/{}", | |
| frameTime, mLogTag, totalCount, jankCount, | |
| mAccumulatedJankCount, mAccumulatedTotalCount); | |
| if (DEBUG_INPUT_JANK_TRACKER) { | |
| for (size_t i = 0; i < mPendingFrames.size(); i++) { | |
| const auto& f = mPendingFrames[i]; | |
| LOG(INFO) << std::format(" [frameTime:{}] PendingFrame[{}]: start={} end={} " | |
| "consumed={} expected={}", | |
| frameTime, i, f.start, f.end, f.consumedCount, | |
| f.expectedCount); | |
| } | |
| for (size_t i = 0; i < mConsumedEvents.size(); i++) { | |
| const auto& e = mConsumedEvents[i]; | |
| LOG(INFO) << std::format(" [frameTime:{}] EventRecord[{}]: action={} time={}", | |
| frameTime, i, actionToString(e.action), e.eventTime); | |
| } | |
| } | |
| } | |
| void InputJankTracker::GestureTracker::evaluateFrameJank(nsecs_t frameTime, bool isGestureEnd, | |
| DeviceStats& deviceStats) { | |
| if ((frameTime < 0) || (mLastFrameTime < 0)) { | |
| return; | |
| } | |
| if (frameTime != mLastFrameTime) { | |
| if (mPendingFrames.size() >= MAX_PENDING_FRAMES) { | |
| LOG_IF(WARNING, DEBUG_INPUT_JANK_TRACKER) | |
| << std::format("mPendingFrames exceeded capacity ({}), dropping oldest frame", | |
| MAX_PENDING_FRAMES); | |
| mPendingFrames.pop_front(); | |
| } | |
| mPendingFrames.push_back({mLastFrameTime, frameTime, mConsumedEvents.size(), 0}); | |
| } | |
| if (mPendingFrames.empty()) { | |
| mConsumedEvents.clear(); | |
| return; | |
| } | |
| if (mConsumedEvents.empty()) { | |
| if (isGestureEnd) { | |
| mPendingFrames.clear(); | |
| } | |
| return; | |
| } | |
| mapEventsToPendingFrames(); | |
| auto [jankCount, totalCount, remainingFrames] = determineJank(isGestureEnd); | |
| if (totalCount > 0) { | |
| updateTelemetry(totalCount, jankCount, /*byref*/ deviceStats); | |
| ATRACE_NAME_IF(ATRACE_ENABLED(), | |
| std::format("InputJankEval [{}]: jank={}/{} (accum={}/{})", mLogTag, | |
| jankCount, totalCount, mAccumulatedJankCount, | |
| mAccumulatedTotalCount)); | |
| if (jankCount > 0) { | |
| logJank(frameTime, jankCount, totalCount); | |
| } | |
| } | |
| if (isGestureEnd) { | |
| mPendingFrames.clear(); | |
| } else { | |
| mPendingFrames = std::move(remainingFrames); | |
| } | |
| mConsumedEvents.clear(); | |
| } | |
| } // namespace android |