Dominik Laskowski | 5a5e01e | 2022-07-08 07:52:44 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2022 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 | |
| 17 | #define LOG_TAG "CompositorTiming" |
| 18 | |
| 19 | #include <cutils/compiler.h> |
| 20 | #include <gui/CompositorTiming.h> |
| 21 | #include <log/log.h> |
| 22 | |
| 23 | namespace android::gui { |
| 24 | |
| 25 | CompositorTiming::CompositorTiming(nsecs_t vsyncDeadline, nsecs_t vsyncPeriod, nsecs_t vsyncPhase, |
| 26 | nsecs_t presentLatency) { |
| 27 | if (CC_UNLIKELY(vsyncPeriod <= 0)) { |
| 28 | ALOGE("Invalid VSYNC period"); |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | const nsecs_t idealLatency = [=] { |
| 33 | // Modulo rounds toward 0 not INT64_MIN, so treat signs separately. |
| 34 | if (vsyncPhase < 0) return -vsyncPhase % vsyncPeriod; |
| 35 | |
| 36 | const nsecs_t latency = (vsyncPeriod - vsyncPhase) % vsyncPeriod; |
| 37 | return latency > 0 ? latency : vsyncPeriod; |
| 38 | }(); |
| 39 | |
| 40 | // Snap the latency to a value that removes scheduling jitter from the composite and present |
| 41 | // times, which often have >1ms of jitter. Reducing jitter is important if an app attempts to |
| 42 | // extrapolate something like user input to an accurate present time. Snapping also allows an |
| 43 | // app to precisely calculate vsyncPhase with (presentLatency % interval). |
| 44 | const nsecs_t bias = vsyncPeriod / 2; |
| 45 | const nsecs_t extraVsyncs = (presentLatency - idealLatency + bias) / vsyncPeriod; |
| 46 | const nsecs_t snappedLatency = |
| 47 | extraVsyncs > 0 ? idealLatency + extraVsyncs * vsyncPeriod : idealLatency; |
| 48 | |
| 49 | this->deadline = vsyncDeadline - idealLatency; |
| 50 | this->interval = vsyncPeriod; |
| 51 | this->presentLatency = snappedLatency; |
| 52 | } |
| 53 | |
| 54 | } // namespace android::gui |