• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 package android.view;
18 
19 import static android.view.DisplayEventReceiver.VSYNC_SOURCE_APP;
20 import static android.view.DisplayEventReceiver.VSYNC_SOURCE_SURFACE_FLINGER;
21 
22 import android.annotation.TestApi;
23 import android.annotation.UnsupportedAppUsage;
24 import android.graphics.FrameInfo;
25 import android.hardware.display.DisplayManagerGlobal;
26 import android.os.Build;
27 import android.os.Handler;
28 import android.os.Looper;
29 import android.os.Message;
30 import android.os.SystemClock;
31 import android.os.SystemProperties;
32 import android.os.Trace;
33 import android.util.Log;
34 import android.util.TimeUtils;
35 import android.view.animation.AnimationUtils;
36 
37 import java.io.PrintWriter;
38 
39 /**
40  * Coordinates the timing of animations, input and drawing.
41  * <p>
42  * The choreographer receives timing pulses (such as vertical synchronization)
43  * from the display subsystem then schedules work to occur as part of rendering
44  * the next display frame.
45  * </p><p>
46  * Applications typically interact with the choreographer indirectly using
47  * higher level abstractions in the animation framework or the view hierarchy.
48  * Here are some examples of things you can do using the higher-level APIs.
49  * </p>
50  * <ul>
51  * <li>To post an animation to be processed on a regular time basis synchronized with
52  * display frame rendering, use {@link android.animation.ValueAnimator#start}.</li>
53  * <li>To post a {@link Runnable} to be invoked once at the beginning of the next display
54  * frame, use {@link View#postOnAnimation}.</li>
55  * <li>To post a {@link Runnable} to be invoked once at the beginning of the next display
56  * frame after a delay, use {@link View#postOnAnimationDelayed}.</li>
57  * <li>To post a call to {@link View#invalidate()} to occur once at the beginning of the
58  * next display frame, use {@link View#postInvalidateOnAnimation()} or
59  * {@link View#postInvalidateOnAnimation(int, int, int, int)}.</li>
60  * <li>To ensure that the contents of a {@link View} scroll smoothly and are drawn in
61  * sync with display frame rendering, do nothing.  This already happens automatically.
62  * {@link View#onDraw} will be called at the appropriate time.</li>
63  * </ul>
64  * <p>
65  * However, there are a few cases where you might want to use the functions of the
66  * choreographer directly in your application.  Here are some examples.
67  * </p>
68  * <ul>
69  * <li>If your application does its rendering in a different thread, possibly using GL,
70  * or does not use the animation framework or view hierarchy at all
71  * and you want to ensure that it is appropriately synchronized with the display, then use
72  * {@link Choreographer#postFrameCallback}.</li>
73  * <li>... and that's about it.</li>
74  * </ul>
75  * <p>
76  * Each {@link Looper} thread has its own choreographer.  Other threads can
77  * post callbacks to run on the choreographer but they will run on the {@link Looper}
78  * to which the choreographer belongs.
79  * </p>
80  */
81 public final class Choreographer {
82     private static final String TAG = "Choreographer";
83 
84     // Prints debug messages about jank which was detected (low volume).
85     private static final boolean DEBUG_JANK = false;
86 
87     // Prints debug messages about every frame and callback registered (high volume).
88     private static final boolean DEBUG_FRAMES = false;
89 
90     // The default amount of time in ms between animation frames.
91     // When vsync is not enabled, we want to have some idea of how long we should
92     // wait before posting the next animation message.  It is important that the
93     // default value be less than the true inter-frame delay on all devices to avoid
94     // situations where we might skip frames by waiting too long (we must compensate
95     // for jitter and hardware variations).  Regardless of this value, the animation
96     // and display loop is ultimately rate-limited by how fast new graphics buffers can
97     // be dequeued.
98     private static final long DEFAULT_FRAME_DELAY = 10;
99 
100     // The number of milliseconds between animation frames.
101     private static volatile long sFrameDelay = DEFAULT_FRAME_DELAY;
102 
103     // Thread local storage for the choreographer.
104     private static final ThreadLocal<Choreographer> sThreadInstance =
105             new ThreadLocal<Choreographer>() {
106         @Override
107         protected Choreographer initialValue() {
108             Looper looper = Looper.myLooper();
109             if (looper == null) {
110                 throw new IllegalStateException("The current thread must have a looper!");
111             }
112             Choreographer choreographer = new Choreographer(looper, VSYNC_SOURCE_APP);
113             if (looper == Looper.getMainLooper()) {
114                 mMainInstance = choreographer;
115             }
116             return choreographer;
117         }
118     };
119 
120     private static volatile Choreographer mMainInstance;
121 
122     // Thread local storage for the SF choreographer.
123     private static final ThreadLocal<Choreographer> sSfThreadInstance =
124             new ThreadLocal<Choreographer>() {
125                 @Override
126                 protected Choreographer initialValue() {
127                     Looper looper = Looper.myLooper();
128                     if (looper == null) {
129                         throw new IllegalStateException("The current thread must have a looper!");
130                     }
131                     return new Choreographer(looper, VSYNC_SOURCE_SURFACE_FLINGER);
132                 }
133             };
134 
135     // Enable/disable vsync for animations and drawing.
136     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769497)
137     private static final boolean USE_VSYNC = SystemProperties.getBoolean(
138             "debug.choreographer.vsync", true);
139 
140     // Enable/disable using the frame time instead of returning now.
141     private static final boolean USE_FRAME_TIME = SystemProperties.getBoolean(
142             "debug.choreographer.frametime", true);
143 
144     // Set a limit to warn about skipped frames.
145     // Skipped frames imply jank.
146     private static final int SKIPPED_FRAME_WARNING_LIMIT = SystemProperties.getInt(
147             "debug.choreographer.skipwarning", 30);
148 
149     private static final int MSG_DO_FRAME = 0;
150     private static final int MSG_DO_SCHEDULE_VSYNC = 1;
151     private static final int MSG_DO_SCHEDULE_CALLBACK = 2;
152 
153     // All frame callbacks posted by applications have this token.
154     private static final Object FRAME_CALLBACK_TOKEN = new Object() {
155         public String toString() { return "FRAME_CALLBACK_TOKEN"; }
156     };
157 
158     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
159     private final Object mLock = new Object();
160 
161     private final Looper mLooper;
162     private final FrameHandler mHandler;
163 
164     // The display event receiver can only be accessed by the looper thread to which
165     // it is attached.  We take care to ensure that we post message to the looper
166     // if appropriate when interacting with the display event receiver.
167     @UnsupportedAppUsage
168     private final FrameDisplayEventReceiver mDisplayEventReceiver;
169 
170     private CallbackRecord mCallbackPool;
171 
172     @UnsupportedAppUsage
173     private final CallbackQueue[] mCallbackQueues;
174 
175     private boolean mFrameScheduled;
176     private boolean mCallbacksRunning;
177     @UnsupportedAppUsage
178     private long mLastFrameTimeNanos;
179     @UnsupportedAppUsage
180     private long mFrameIntervalNanos;
181     private boolean mDebugPrintNextFrameTimeDelta;
182     private int mFPSDivisor = 1;
183 
184     /**
185      * Contains information about the current frame for jank-tracking,
186      * mainly timings of key events along with a bit of metadata about
187      * view tree state
188      *
189      * TODO: Is there a better home for this? Currently Choreographer
190      * is the only one with CALLBACK_ANIMATION start time, hence why this
191      * resides here.
192      *
193      * @hide
194      */
195     FrameInfo mFrameInfo = new FrameInfo();
196 
197     /**
198      * Must be kept in sync with CALLBACK_* ints below, used to index into this array.
199      * @hide
200      */
201     private static final String[] CALLBACK_TRACE_TITLES = {
202             "input", "animation", "insets_animation", "traversal", "commit"
203     };
204 
205     /**
206      * Callback type: Input callback.  Runs first.
207      * @hide
208      */
209     public static final int CALLBACK_INPUT = 0;
210 
211     /**
212      * Callback type: Animation callback.  Runs before {@link #CALLBACK_INSETS_ANIMATION}.
213      * @hide
214      */
215     @TestApi
216     public static final int CALLBACK_ANIMATION = 1;
217 
218     /**
219      * Callback type: Animation callback to handle inset updates. This is separate from
220      * {@link #CALLBACK_ANIMATION} as we need to "gather" all inset animation updates via
221      * {@link WindowInsetsAnimationController#changeInsets} for multiple ongoing animations but then
222      * update the whole view system with a single callback to {@link View#dispatchWindowInsetsAnimationProgress}
223      * that contains all the combined updated insets.
224      * <p>
225      * Both input and animation may change insets, so we need to run this after these callbacks, but
226      * before traversals.
227      * <p>
228      * Runs before traversals.
229      * @hide
230      */
231     public static final int CALLBACK_INSETS_ANIMATION = 2;
232 
233     /**
234      * Callback type: Traversal callback.  Handles layout and draw.  Runs
235      * after all other asynchronous messages have been handled.
236      * @hide
237      */
238     public static final int CALLBACK_TRAVERSAL = 3;
239 
240     /**
241      * Callback type: Commit callback.  Handles post-draw operations for the frame.
242      * Runs after traversal completes.  The {@link #getFrameTime() frame time} reported
243      * during this callback may be updated to reflect delays that occurred while
244      * traversals were in progress in case heavy layout operations caused some frames
245      * to be skipped.  The frame time reported during this callback provides a better
246      * estimate of the start time of the frame in which animations (and other updates
247      * to the view hierarchy state) actually took effect.
248      * @hide
249      */
250     public static final int CALLBACK_COMMIT = 4;
251 
252     private static final int CALLBACK_LAST = CALLBACK_COMMIT;
253 
Choreographer(Looper looper, int vsyncSource)254     private Choreographer(Looper looper, int vsyncSource) {
255         mLooper = looper;
256         mHandler = new FrameHandler(looper);
257         mDisplayEventReceiver = USE_VSYNC
258                 ? new FrameDisplayEventReceiver(looper, vsyncSource)
259                 : null;
260         mLastFrameTimeNanos = Long.MIN_VALUE;
261 
262         mFrameIntervalNanos = (long)(1000000000 / getRefreshRate());
263 
264         mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1];
265         for (int i = 0; i <= CALLBACK_LAST; i++) {
266             mCallbackQueues[i] = new CallbackQueue();
267         }
268         // b/68769804: For low FPS experiments.
269         setFPSDivisor(SystemProperties.getInt(ThreadedRenderer.DEBUG_FPS_DIVISOR, 1));
270     }
271 
getRefreshRate()272     private static float getRefreshRate() {
273         DisplayInfo di = DisplayManagerGlobal.getInstance().getDisplayInfo(
274                 Display.DEFAULT_DISPLAY);
275         return di.getMode().getRefreshRate();
276     }
277 
278     /**
279      * Gets the choreographer for the calling thread.  Must be called from
280      * a thread that already has a {@link android.os.Looper} associated with it.
281      *
282      * @return The choreographer for this thread.
283      * @throws IllegalStateException if the thread does not have a looper.
284      */
getInstance()285     public static Choreographer getInstance() {
286         return sThreadInstance.get();
287     }
288 
289     /**
290      * @hide
291      */
292     @UnsupportedAppUsage
getSfInstance()293     public static Choreographer getSfInstance() {
294         return sSfThreadInstance.get();
295     }
296 
297     /**
298      * @return The Choreographer of the main thread, if it exists, or {@code null} otherwise.
299      * @hide
300      */
getMainThreadInstance()301     public static Choreographer getMainThreadInstance() {
302         return mMainInstance;
303     }
304 
305     /** Destroys the calling thread's choreographer
306      * @hide
307      */
releaseInstance()308     public static void releaseInstance() {
309         Choreographer old = sThreadInstance.get();
310         sThreadInstance.remove();
311         old.dispose();
312     }
313 
dispose()314     private void dispose() {
315         mDisplayEventReceiver.dispose();
316     }
317 
318     /**
319      * The amount of time, in milliseconds, between each frame of the animation.
320      * <p>
321      * This is a requested time that the animation will attempt to honor, but the actual delay
322      * between frames may be different, depending on system load and capabilities. This is a static
323      * function because the same delay will be applied to all animations, since they are all
324      * run off of a single timing loop.
325      * </p><p>
326      * The frame delay may be ignored when the animation system uses an external timing
327      * source, such as the display refresh rate (vsync), to govern animations.
328      * </p>
329      *
330      * @return the requested time between frames, in milliseconds
331      * @hide
332      */
333     @TestApi
getFrameDelay()334     public static long getFrameDelay() {
335         return sFrameDelay;
336     }
337 
338     /**
339      * The amount of time, in milliseconds, between each frame of the animation.
340      * <p>
341      * This is a requested time that the animation will attempt to honor, but the actual delay
342      * between frames may be different, depending on system load and capabilities. This is a static
343      * function because the same delay will be applied to all animations, since they are all
344      * run off of a single timing loop.
345      * </p><p>
346      * The frame delay may be ignored when the animation system uses an external timing
347      * source, such as the display refresh rate (vsync), to govern animations.
348      * </p>
349      *
350      * @param frameDelay the requested time between frames, in milliseconds
351      * @hide
352      */
353     @TestApi
setFrameDelay(long frameDelay)354     public static void setFrameDelay(long frameDelay) {
355         sFrameDelay = frameDelay;
356     }
357 
358     /**
359      * Subtracts typical frame delay time from a delay interval in milliseconds.
360      * <p>
361      * This method can be used to compensate for animation delay times that have baked
362      * in assumptions about the frame delay.  For example, it's quite common for code to
363      * assume a 60Hz frame time and bake in a 16ms delay.  When we call
364      * {@link #postAnimationCallbackDelayed} we want to know how long to wait before
365      * posting the animation callback but let the animation timer take care of the remaining
366      * frame delay time.
367      * </p><p>
368      * This method is somewhat conservative about how much of the frame delay it
369      * subtracts.  It uses the same value returned by {@link #getFrameDelay} which by
370      * default is 10ms even though many parts of the system assume 16ms.  Consequently,
371      * we might still wait 6ms before posting an animation callback that we want to run
372      * on the next frame, but this is much better than waiting a whole 16ms and likely
373      * missing the deadline.
374      * </p>
375      *
376      * @param delayMillis The original delay time including an assumed frame delay.
377      * @return The adjusted delay time with the assumed frame delay subtracted out.
378      * @hide
379      */
subtractFrameDelay(long delayMillis)380     public static long subtractFrameDelay(long delayMillis) {
381         final long frameDelay = sFrameDelay;
382         return delayMillis <= frameDelay ? 0 : delayMillis - frameDelay;
383     }
384 
385     /**
386      * @return The refresh rate as the nanoseconds between frames
387      * @hide
388      */
getFrameIntervalNanos()389     public long getFrameIntervalNanos() {
390         return mFrameIntervalNanos;
391     }
392 
dump(String prefix, PrintWriter writer)393     void dump(String prefix, PrintWriter writer) {
394         String innerPrefix = prefix + "  ";
395         writer.print(prefix); writer.println("Choreographer:");
396         writer.print(innerPrefix); writer.print("mFrameScheduled=");
397                 writer.println(mFrameScheduled);
398         writer.print(innerPrefix); writer.print("mLastFrameTime=");
399                 writer.println(TimeUtils.formatUptime(mLastFrameTimeNanos / 1000000));
400     }
401 
402     /**
403      * Posts a callback to run on the next frame.
404      * <p>
405      * The callback runs once then is automatically removed.
406      * </p>
407      *
408      * @param callbackType The callback type.
409      * @param action The callback action to run during the next frame.
410      * @param token The callback token, or null if none.
411      *
412      * @see #removeCallbacks
413      * @hide
414      */
415     @TestApi
postCallback(int callbackType, Runnable action, Object token)416     public void postCallback(int callbackType, Runnable action, Object token) {
417         postCallbackDelayed(callbackType, action, token, 0);
418     }
419 
420     /**
421      * Posts a callback to run on the next frame after the specified delay.
422      * <p>
423      * The callback runs once then is automatically removed.
424      * </p>
425      *
426      * @param callbackType The callback type.
427      * @param action The callback action to run during the next frame after the specified delay.
428      * @param token The callback token, or null if none.
429      * @param delayMillis The delay time in milliseconds.
430      *
431      * @see #removeCallback
432      * @hide
433      */
434     @TestApi
postCallbackDelayed(int callbackType, Runnable action, Object token, long delayMillis)435     public void postCallbackDelayed(int callbackType,
436             Runnable action, Object token, long delayMillis) {
437         if (action == null) {
438             throw new IllegalArgumentException("action must not be null");
439         }
440         if (callbackType < 0 || callbackType > CALLBACK_LAST) {
441             throw new IllegalArgumentException("callbackType is invalid");
442         }
443 
444         postCallbackDelayedInternal(callbackType, action, token, delayMillis);
445     }
446 
postCallbackDelayedInternal(int callbackType, Object action, Object token, long delayMillis)447     private void postCallbackDelayedInternal(int callbackType,
448             Object action, Object token, long delayMillis) {
449         if (DEBUG_FRAMES) {
450             Log.d(TAG, "PostCallback: type=" + callbackType
451                     + ", action=" + action + ", token=" + token
452                     + ", delayMillis=" + delayMillis);
453         }
454 
455         synchronized (mLock) {
456             final long now = SystemClock.uptimeMillis();
457             final long dueTime = now + delayMillis;
458             mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);
459 
460             if (dueTime <= now) {
461                 scheduleFrameLocked(now);
462             } else {
463                 Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);
464                 msg.arg1 = callbackType;
465                 msg.setAsynchronous(true);
466                 mHandler.sendMessageAtTime(msg, dueTime);
467             }
468         }
469     }
470 
471     /**
472      * Removes callbacks that have the specified action and token.
473      *
474      * @param callbackType The callback type.
475      * @param action The action property of the callbacks to remove, or null to remove
476      * callbacks with any action.
477      * @param token The token property of the callbacks to remove, or null to remove
478      * callbacks with any token.
479      *
480      * @see #postCallback
481      * @see #postCallbackDelayed
482      * @hide
483      */
484     @TestApi
removeCallbacks(int callbackType, Runnable action, Object token)485     public void removeCallbacks(int callbackType, Runnable action, Object token) {
486         if (callbackType < 0 || callbackType > CALLBACK_LAST) {
487             throw new IllegalArgumentException("callbackType is invalid");
488         }
489 
490         removeCallbacksInternal(callbackType, action, token);
491     }
492 
removeCallbacksInternal(int callbackType, Object action, Object token)493     private void removeCallbacksInternal(int callbackType, Object action, Object token) {
494         if (DEBUG_FRAMES) {
495             Log.d(TAG, "RemoveCallbacks: type=" + callbackType
496                     + ", action=" + action + ", token=" + token);
497         }
498 
499         synchronized (mLock) {
500             mCallbackQueues[callbackType].removeCallbacksLocked(action, token);
501             if (action != null && token == null) {
502                 mHandler.removeMessages(MSG_DO_SCHEDULE_CALLBACK, action);
503             }
504         }
505     }
506 
507     /**
508      * Posts a frame callback to run on the next frame.
509      * <p>
510      * The callback runs once then is automatically removed.
511      * </p>
512      *
513      * @param callback The frame callback to run during the next frame.
514      *
515      * @see #postFrameCallbackDelayed
516      * @see #removeFrameCallback
517      */
postFrameCallback(FrameCallback callback)518     public void postFrameCallback(FrameCallback callback) {
519         postFrameCallbackDelayed(callback, 0);
520     }
521 
522     /**
523      * Posts a frame callback to run on the next frame after the specified delay.
524      * <p>
525      * The callback runs once then is automatically removed.
526      * </p>
527      *
528      * @param callback The frame callback to run during the next frame.
529      * @param delayMillis The delay time in milliseconds.
530      *
531      * @see #postFrameCallback
532      * @see #removeFrameCallback
533      */
postFrameCallbackDelayed(FrameCallback callback, long delayMillis)534     public void postFrameCallbackDelayed(FrameCallback callback, long delayMillis) {
535         if (callback == null) {
536             throw new IllegalArgumentException("callback must not be null");
537         }
538 
539         postCallbackDelayedInternal(CALLBACK_ANIMATION,
540                 callback, FRAME_CALLBACK_TOKEN, delayMillis);
541     }
542 
543     /**
544      * Removes a previously posted frame callback.
545      *
546      * @param callback The frame callback to remove.
547      *
548      * @see #postFrameCallback
549      * @see #postFrameCallbackDelayed
550      */
removeFrameCallback(FrameCallback callback)551     public void removeFrameCallback(FrameCallback callback) {
552         if (callback == null) {
553             throw new IllegalArgumentException("callback must not be null");
554         }
555 
556         removeCallbacksInternal(CALLBACK_ANIMATION, callback, FRAME_CALLBACK_TOKEN);
557     }
558 
559     /**
560      * Gets the time when the current frame started.
561      * <p>
562      * This method provides the time in milliseconds when the frame started being rendered.
563      * The frame time provides a stable time base for synchronizing animations
564      * and drawing.  It should be used instead of {@link SystemClock#uptimeMillis()}
565      * or {@link System#nanoTime()} for animations and drawing in the UI.  Using the frame
566      * time helps to reduce inter-frame jitter because the frame time is fixed at the time
567      * the frame was scheduled to start, regardless of when the animations or drawing
568      * callback actually runs.  All callbacks that run as part of rendering a frame will
569      * observe the same frame time so using the frame time also helps to synchronize effects
570      * that are performed by different callbacks.
571      * </p><p>
572      * Please note that the framework already takes care to process animations and
573      * drawing using the frame time as a stable time base.  Most applications should
574      * not need to use the frame time information directly.
575      * </p><p>
576      * This method should only be called from within a callback.
577      * </p>
578      *
579      * @return The frame start time, in the {@link SystemClock#uptimeMillis()} time base.
580      *
581      * @throws IllegalStateException if no frame is in progress.
582      * @hide
583      */
584     @UnsupportedAppUsage
getFrameTime()585     public long getFrameTime() {
586         return getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
587     }
588 
589     /**
590      * Same as {@link #getFrameTime()} but with nanosecond precision.
591      *
592      * @return The frame start time, in the {@link System#nanoTime()} time base.
593      *
594      * @throws IllegalStateException if no frame is in progress.
595      * @hide
596      */
597     @UnsupportedAppUsage
getFrameTimeNanos()598     public long getFrameTimeNanos() {
599         synchronized (mLock) {
600             if (!mCallbacksRunning) {
601                 throw new IllegalStateException("This method must only be called as "
602                         + "part of a callback while a frame is in progress.");
603             }
604             return USE_FRAME_TIME ? mLastFrameTimeNanos : System.nanoTime();
605         }
606     }
607 
608     /**
609      * Like {@link #getLastFrameTimeNanos}, but always returns the last frame time, not matter
610      * whether callbacks are currently running.
611      * @return The frame start time of the last frame, in the {@link System#nanoTime()} time base.
612      * @hide
613      */
getLastFrameTimeNanos()614     public long getLastFrameTimeNanos() {
615         synchronized (mLock) {
616             return USE_FRAME_TIME ? mLastFrameTimeNanos : System.nanoTime();
617         }
618     }
619 
scheduleFrameLocked(long now)620     private void scheduleFrameLocked(long now) {
621         if (!mFrameScheduled) {
622             mFrameScheduled = true;
623             if (USE_VSYNC) {
624                 if (DEBUG_FRAMES) {
625                     Log.d(TAG, "Scheduling next frame on vsync.");
626                 }
627 
628                 // If running on the Looper thread, then schedule the vsync immediately,
629                 // otherwise post a message to schedule the vsync from the UI thread
630                 // as soon as possible.
631                 if (isRunningOnLooperThreadLocked()) {
632                     scheduleVsyncLocked();
633                 } else {
634                     Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC);
635                     msg.setAsynchronous(true);
636                     mHandler.sendMessageAtFrontOfQueue(msg);
637                 }
638             } else {
639                 final long nextFrameTime = Math.max(
640                         mLastFrameTimeNanos / TimeUtils.NANOS_PER_MS + sFrameDelay, now);
641                 if (DEBUG_FRAMES) {
642                     Log.d(TAG, "Scheduling next frame in " + (nextFrameTime - now) + " ms.");
643                 }
644                 Message msg = mHandler.obtainMessage(MSG_DO_FRAME);
645                 msg.setAsynchronous(true);
646                 mHandler.sendMessageAtTime(msg, nextFrameTime);
647             }
648         }
649     }
650 
setFPSDivisor(int divisor)651     void setFPSDivisor(int divisor) {
652         if (divisor <= 0) divisor = 1;
653         mFPSDivisor = divisor;
654         ThreadedRenderer.setFPSDivisor(divisor);
655     }
656 
657     @UnsupportedAppUsage
doFrame(long frameTimeNanos, int frame)658     void doFrame(long frameTimeNanos, int frame) {
659         final long startNanos;
660         synchronized (mLock) {
661             if (!mFrameScheduled) {
662                 return; // no work to do
663             }
664 
665             if (DEBUG_JANK && mDebugPrintNextFrameTimeDelta) {
666                 mDebugPrintNextFrameTimeDelta = false;
667                 Log.d(TAG, "Frame time delta: "
668                         + ((frameTimeNanos - mLastFrameTimeNanos) * 0.000001f) + " ms");
669             }
670 
671             long intendedFrameTimeNanos = frameTimeNanos;
672             startNanos = System.nanoTime();
673             final long jitterNanos = startNanos - frameTimeNanos;
674             if (jitterNanos >= mFrameIntervalNanos) {
675                 final long skippedFrames = jitterNanos / mFrameIntervalNanos;
676                 if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) {
677                     Log.i(TAG, "Skipped " + skippedFrames + " frames!  "
678                             + "The application may be doing too much work on its main thread.");
679                 }
680                 final long lastFrameOffset = jitterNanos % mFrameIntervalNanos;
681                 if (DEBUG_JANK) {
682                     Log.d(TAG, "Missed vsync by " + (jitterNanos * 0.000001f) + " ms "
683                             + "which is more than the frame interval of "
684                             + (mFrameIntervalNanos * 0.000001f) + " ms!  "
685                             + "Skipping " + skippedFrames + " frames and setting frame "
686                             + "time to " + (lastFrameOffset * 0.000001f) + " ms in the past.");
687                 }
688                 frameTimeNanos = startNanos - lastFrameOffset;
689             }
690 
691             if (frameTimeNanos < mLastFrameTimeNanos) {
692                 if (DEBUG_JANK) {
693                     Log.d(TAG, "Frame time appears to be going backwards.  May be due to a "
694                             + "previously skipped frame.  Waiting for next vsync.");
695                 }
696                 scheduleVsyncLocked();
697                 return;
698             }
699 
700             if (mFPSDivisor > 1) {
701                 long timeSinceVsync = frameTimeNanos - mLastFrameTimeNanos;
702                 if (timeSinceVsync < (mFrameIntervalNanos * mFPSDivisor) && timeSinceVsync > 0) {
703                     scheduleVsyncLocked();
704                     return;
705                 }
706             }
707 
708             mFrameInfo.setVsync(intendedFrameTimeNanos, frameTimeNanos);
709             mFrameScheduled = false;
710             mLastFrameTimeNanos = frameTimeNanos;
711         }
712 
713         try {
714             Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Choreographer#doFrame");
715             AnimationUtils.lockAnimationClock(frameTimeNanos / TimeUtils.NANOS_PER_MS);
716 
717             mFrameInfo.markInputHandlingStart();
718             doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos);
719 
720             mFrameInfo.markAnimationsStart();
721             doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos);
722             doCallbacks(Choreographer.CALLBACK_INSETS_ANIMATION, frameTimeNanos);
723 
724             mFrameInfo.markPerformTraversalsStart();
725             doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
726 
727             doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos);
728         } finally {
729             AnimationUtils.unlockAnimationClock();
730             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
731         }
732 
733         if (DEBUG_FRAMES) {
734             final long endNanos = System.nanoTime();
735             Log.d(TAG, "Frame " + frame + ": Finished, took "
736                     + (endNanos - startNanos) * 0.000001f + " ms, latency "
737                     + (startNanos - frameTimeNanos) * 0.000001f + " ms.");
738         }
739     }
740 
doCallbacks(int callbackType, long frameTimeNanos)741     void doCallbacks(int callbackType, long frameTimeNanos) {
742         CallbackRecord callbacks;
743         synchronized (mLock) {
744             // We use "now" to determine when callbacks become due because it's possible
745             // for earlier processing phases in a frame to post callbacks that should run
746             // in a following phase, such as an input event that causes an animation to start.
747             final long now = System.nanoTime();
748             callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked(
749                     now / TimeUtils.NANOS_PER_MS);
750             if (callbacks == null) {
751                 return;
752             }
753             mCallbacksRunning = true;
754 
755             // Update the frame time if necessary when committing the frame.
756             // We only update the frame time if we are more than 2 frames late reaching
757             // the commit phase.  This ensures that the frame time which is observed by the
758             // callbacks will always increase from one frame to the next and never repeat.
759             // We never want the next frame's starting frame time to end up being less than
760             // or equal to the previous frame's commit frame time.  Keep in mind that the
761             // next frame has most likely already been scheduled by now so we play it
762             // safe by ensuring the commit time is always at least one frame behind.
763             if (callbackType == Choreographer.CALLBACK_COMMIT) {
764                 final long jitterNanos = now - frameTimeNanos;
765                 Trace.traceCounter(Trace.TRACE_TAG_VIEW, "jitterNanos", (int) jitterNanos);
766                 if (jitterNanos >= 2 * mFrameIntervalNanos) {
767                     final long lastFrameOffset = jitterNanos % mFrameIntervalNanos
768                             + mFrameIntervalNanos;
769                     if (DEBUG_JANK) {
770                         Log.d(TAG, "Commit callback delayed by " + (jitterNanos * 0.000001f)
771                                 + " ms which is more than twice the frame interval of "
772                                 + (mFrameIntervalNanos * 0.000001f) + " ms!  "
773                                 + "Setting frame time to " + (lastFrameOffset * 0.000001f)
774                                 + " ms in the past.");
775                         mDebugPrintNextFrameTimeDelta = true;
776                     }
777                     frameTimeNanos = now - lastFrameOffset;
778                     mLastFrameTimeNanos = frameTimeNanos;
779                 }
780             }
781         }
782         try {
783             Trace.traceBegin(Trace.TRACE_TAG_VIEW, CALLBACK_TRACE_TITLES[callbackType]);
784             for (CallbackRecord c = callbacks; c != null; c = c.next) {
785                 if (DEBUG_FRAMES) {
786                     Log.d(TAG, "RunCallback: type=" + callbackType
787                             + ", action=" + c.action + ", token=" + c.token
788                             + ", latencyMillis=" + (SystemClock.uptimeMillis() - c.dueTime));
789                 }
790                 c.run(frameTimeNanos);
791             }
792         } finally {
793             synchronized (mLock) {
794                 mCallbacksRunning = false;
795                 do {
796                     final CallbackRecord next = callbacks.next;
797                     recycleCallbackLocked(callbacks);
798                     callbacks = next;
799                 } while (callbacks != null);
800             }
801             Trace.traceEnd(Trace.TRACE_TAG_VIEW);
802         }
803     }
804 
doScheduleVsync()805     void doScheduleVsync() {
806         synchronized (mLock) {
807             if (mFrameScheduled) {
808                 scheduleVsyncLocked();
809             }
810         }
811     }
812 
doScheduleCallback(int callbackType)813     void doScheduleCallback(int callbackType) {
814         synchronized (mLock) {
815             if (!mFrameScheduled) {
816                 final long now = SystemClock.uptimeMillis();
817                 if (mCallbackQueues[callbackType].hasDueCallbacksLocked(now)) {
818                     scheduleFrameLocked(now);
819                 }
820             }
821         }
822     }
823 
824     @UnsupportedAppUsage
scheduleVsyncLocked()825     private void scheduleVsyncLocked() {
826         mDisplayEventReceiver.scheduleVsync();
827     }
828 
isRunningOnLooperThreadLocked()829     private boolean isRunningOnLooperThreadLocked() {
830         return Looper.myLooper() == mLooper;
831     }
832 
obtainCallbackLocked(long dueTime, Object action, Object token)833     private CallbackRecord obtainCallbackLocked(long dueTime, Object action, Object token) {
834         CallbackRecord callback = mCallbackPool;
835         if (callback == null) {
836             callback = new CallbackRecord();
837         } else {
838             mCallbackPool = callback.next;
839             callback.next = null;
840         }
841         callback.dueTime = dueTime;
842         callback.action = action;
843         callback.token = token;
844         return callback;
845     }
846 
recycleCallbackLocked(CallbackRecord callback)847     private void recycleCallbackLocked(CallbackRecord callback) {
848         callback.action = null;
849         callback.token = null;
850         callback.next = mCallbackPool;
851         mCallbackPool = callback;
852     }
853 
854     /**
855      * Implement this interface to receive a callback when a new display frame is
856      * being rendered.  The callback is invoked on the {@link Looper} thread to
857      * which the {@link Choreographer} is attached.
858      */
859     public interface FrameCallback {
860         /**
861          * Called when a new display frame is being rendered.
862          * <p>
863          * This method provides the time in nanoseconds when the frame started being rendered.
864          * The frame time provides a stable time base for synchronizing animations
865          * and drawing.  It should be used instead of {@link SystemClock#uptimeMillis()}
866          * or {@link System#nanoTime()} for animations and drawing in the UI.  Using the frame
867          * time helps to reduce inter-frame jitter because the frame time is fixed at the time
868          * the frame was scheduled to start, regardless of when the animations or drawing
869          * callback actually runs.  All callbacks that run as part of rendering a frame will
870          * observe the same frame time so using the frame time also helps to synchronize effects
871          * that are performed by different callbacks.
872          * </p><p>
873          * Please note that the framework already takes care to process animations and
874          * drawing using the frame time as a stable time base.  Most applications should
875          * not need to use the frame time information directly.
876          * </p>
877          *
878          * @param frameTimeNanos The time in nanoseconds when the frame started being rendered,
879          * in the {@link System#nanoTime()} timebase.  Divide this value by {@code 1000000}
880          * to convert it to the {@link SystemClock#uptimeMillis()} time base.
881          */
doFrame(long frameTimeNanos)882         public void doFrame(long frameTimeNanos);
883     }
884 
885     private final class FrameHandler extends Handler {
FrameHandler(Looper looper)886         public FrameHandler(Looper looper) {
887             super(looper);
888         }
889 
890         @Override
handleMessage(Message msg)891         public void handleMessage(Message msg) {
892             switch (msg.what) {
893                 case MSG_DO_FRAME:
894                     doFrame(System.nanoTime(), 0);
895                     break;
896                 case MSG_DO_SCHEDULE_VSYNC:
897                     doScheduleVsync();
898                     break;
899                 case MSG_DO_SCHEDULE_CALLBACK:
900                     doScheduleCallback(msg.arg1);
901                     break;
902             }
903         }
904     }
905 
906     private final class FrameDisplayEventReceiver extends DisplayEventReceiver
907             implements Runnable {
908         private boolean mHavePendingVsync;
909         private long mTimestampNanos;
910         private int mFrame;
911 
FrameDisplayEventReceiver(Looper looper, int vsyncSource)912         public FrameDisplayEventReceiver(Looper looper, int vsyncSource) {
913             super(looper, vsyncSource);
914         }
915 
916         // TODO(b/116025192): physicalDisplayId is ignored because SF only emits VSYNC events for
917         // the internal display and DisplayEventReceiver#scheduleVsync only allows requesting VSYNC
918         // for the internal display implicitly.
919         @Override
onVsync(long timestampNanos, long physicalDisplayId, int frame)920         public void onVsync(long timestampNanos, long physicalDisplayId, int frame) {
921             // Post the vsync event to the Handler.
922             // The idea is to prevent incoming vsync events from completely starving
923             // the message queue.  If there are no messages in the queue with timestamps
924             // earlier than the frame time, then the vsync event will be processed immediately.
925             // Otherwise, messages that predate the vsync event will be handled first.
926             long now = System.nanoTime();
927             if (timestampNanos > now) {
928                 Log.w(TAG, "Frame time is " + ((timestampNanos - now) * 0.000001f)
929                         + " ms in the future!  Check that graphics HAL is generating vsync "
930                         + "timestamps using the correct timebase.");
931                 timestampNanos = now;
932             }
933 
934             if (mHavePendingVsync) {
935                 Log.w(TAG, "Already have a pending vsync event.  There should only be "
936                         + "one at a time.");
937             } else {
938                 mHavePendingVsync = true;
939             }
940 
941             mTimestampNanos = timestampNanos;
942             mFrame = frame;
943             Message msg = Message.obtain(mHandler, this);
944             msg.setAsynchronous(true);
945             mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
946         }
947 
948         @Override
run()949         public void run() {
950             mHavePendingVsync = false;
951             doFrame(mTimestampNanos, mFrame);
952         }
953     }
954 
955     private static final class CallbackRecord {
956         public CallbackRecord next;
957         public long dueTime;
958         public Object action; // Runnable or FrameCallback
959         public Object token;
960 
961         @UnsupportedAppUsage
run(long frameTimeNanos)962         public void run(long frameTimeNanos) {
963             if (token == FRAME_CALLBACK_TOKEN) {
964                 ((FrameCallback)action).doFrame(frameTimeNanos);
965             } else {
966                 ((Runnable)action).run();
967             }
968         }
969     }
970 
971     private final class CallbackQueue {
972         private CallbackRecord mHead;
973 
hasDueCallbacksLocked(long now)974         public boolean hasDueCallbacksLocked(long now) {
975             return mHead != null && mHead.dueTime <= now;
976         }
977 
extractDueCallbacksLocked(long now)978         public CallbackRecord extractDueCallbacksLocked(long now) {
979             CallbackRecord callbacks = mHead;
980             if (callbacks == null || callbacks.dueTime > now) {
981                 return null;
982             }
983 
984             CallbackRecord last = callbacks;
985             CallbackRecord next = last.next;
986             while (next != null) {
987                 if (next.dueTime > now) {
988                     last.next = null;
989                     break;
990                 }
991                 last = next;
992                 next = next.next;
993             }
994             mHead = next;
995             return callbacks;
996         }
997 
998         @UnsupportedAppUsage
addCallbackLocked(long dueTime, Object action, Object token)999         public void addCallbackLocked(long dueTime, Object action, Object token) {
1000             CallbackRecord callback = obtainCallbackLocked(dueTime, action, token);
1001             CallbackRecord entry = mHead;
1002             if (entry == null) {
1003                 mHead = callback;
1004                 return;
1005             }
1006             if (dueTime < entry.dueTime) {
1007                 callback.next = entry;
1008                 mHead = callback;
1009                 return;
1010             }
1011             while (entry.next != null) {
1012                 if (dueTime < entry.next.dueTime) {
1013                     callback.next = entry.next;
1014                     break;
1015                 }
1016                 entry = entry.next;
1017             }
1018             entry.next = callback;
1019         }
1020 
removeCallbacksLocked(Object action, Object token)1021         public void removeCallbacksLocked(Object action, Object token) {
1022             CallbackRecord predecessor = null;
1023             for (CallbackRecord callback = mHead; callback != null;) {
1024                 final CallbackRecord next = callback.next;
1025                 if ((action == null || callback.action == action)
1026                         && (token == null || callback.token == token)) {
1027                     if (predecessor != null) {
1028                         predecessor.next = next;
1029                     } else {
1030                         mHead = next;
1031                     }
1032                     recycleCallbackLocked(callback);
1033                 } else {
1034                     predecessor = callback;
1035                 }
1036                 callback = next;
1037             }
1038         }
1039     }
1040 }
1041