从FrameCallback理解Choreographer原理及简单帧率监控应用

简单来说,Choreographer主要作用是协调动画,输入和绘制的时间,它从显示子系统接收定时脉冲(例如垂直同步),然后安排渲染下一个frame的一部分工作。
自定义FrameCallback

FrameCallback是和Choreographer交互,在下一个frame被渲染时触发的接口类。开发者可以设置自己的FrameCallback。我们就从自定义FrameCallback作为切入口,尝试窥探一下Choreographer的实现原理。简单实现如下:

private static final String TAG = “Choreographer_test”;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView imageView= (ImageView) findViewById(R.id.iv_anim);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final long starTime=System.nanoTime();
            Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
                @Override
                public void doFrame(long frameTimeNanos) {
                    Log.e(TAG,"starTime="+starTime+", frameTimeNanos="+frameTimeNanos+", frameDueTime="+(frameTimeNanos-starTime)/1000000);
                }
            });
        }
    });

}

在这里,我们自定义的FrameCallback只是简单把时间打印了一下。输出如下信息:

E/Choreographer_test: starTime=232157742945242, frameTimeNanos=232157744964255, frameDueTime=2

从log可以看出,这一帧大概2ms就处理完毕。下面我们从源码角度窥探一下它具体的实现原理。
实现原理

  1. 关键成员变量
    构造函数

    private Choreographer(Looper looper) {
    mLooper = looper;
    //1.创建Handler对象,用于处理消息
    mHandler = new FrameHandler(looper);
    //2.创建接收VSYNC信号的对象
    mDisplayEventReceiver = USE_VSYNC ? new FrameDisplayEventReceiver(looper) : null;
    //3.初始化上一次frame渲染的时间点
    mLastFrameTimeNanos = Long.MIN_VALUE;
    //4.帧率,也就是渲染一帧的时间,getRefreshRate是刷新率,一般是60
    mFrameIntervalNanos = (long)(1000000000 / getRefreshRate());
    //5.创建回调队列
    mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1];
    for (int i = 0; i <= CALLBACK_LAST; i++) {
    mCallbackQueues[i] = new CallbackQueue();
    }
    }

FrameHandler

private final class FrameHandler extends Handler {
public FrameHandler(Looper looper) {
super(looper);
}

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_DO_FRAME:
                //渲染下一个frame
                doFrame(System.nanoTime(), 0);
                break;
            case MSG_DO_SCHEDULE_VSYNC:
                //请求VSNYC信号
                doScheduleVsync();
                break;
            case MSG_DO_SCHEDULE_CALLBACK:
                //执行Callback
                doScheduleCallback(msg.arg1);
                break;
        }
    }
}

FrameDisplayEventReceiver

FrameDisplayEventReceiver是DisplayEventReceiver的子类,DisplayEventReceiver是接收VSYNC信息的java层实现。

public abstract class DisplayEventReceiver {
public void onVsync(long timestampNanos, int builtInDisplayId, int frame) {}
public void scheduleVsync() {
if (mReceiverPtr == 0) {
Log.w(TAG, "Attempted to schedule a vertical sync pulse but the display event "
+ “receiver has already been disposed.”);
} else {
nativeScheduleVsync(mReceiverPtr);
}
}
private void dispatchVsync(long timestampNanos, int builtInDisplayId, int frame) {
onVsync(timestampNanos, builtInDisplayId, frame);
}
}

VSYNC信息一般由硬件中断产生,SurfaceFlinger处理。具体实现和监听机制可以参考链接,scheduleVsync方法用于请求VSNYC信号, Native方法接收到VSYNC信息处理后会调用java层dispatchVsync方法,最终调用到FrameDisplayEventReceiver的onVsync方法,具体实现我们一会再说。
CallbackQueue

CallbackQueue是个单链表实现,每种类型的callback(CallbackRecord)按照设置的执行时间(dueTime)顺序排序分别保存在其各自CallbackQueue。在Choreographer中有四种类型callback:Input、Animation、Draw,还有一种是用来解决动画启动问题的。

private final class CallbackQueue {
private CallbackRecord mHead;

    public boolean hasDueCallbacksLocked(long now) {
        return mHead != null && mHead.dueTime <= now;
    }
    //根据当前时间得到callback
    public CallbackRecord extractDueCallbacksLocked(long now) {
          ....
          ....
    }
    //根据时间添加callback
    public void addCallbackLocked(long dueTime, Object action, Object token) {
        ....
        ....
    }
    //移除callback
    public void removeCallbacksLocked(Object action, Object token) {
             ....
             ....
        }
    }
}
  1. 流程分析

大致分析完Choreographer关键的几个成员变量后,我们再回到postFrameCallback方法

public void postFrameCallbackDelayed(FrameCallback callback, long delayMillis) {
    if (callback == null) {
        throw new IllegalArgumentException("callback must not be null");
    }
    //默认为CALLBACK_ANIMATION类型
    postCallbackDelayedInternal(CALLBACK_ANIMATION,
            callback, FRAME_CALLBACK_TOKEN, delayMillis);
}

1
2
3
4
5
6
7
8
9

postCallbackDelayedInternal

private void postCallbackDelayedInternal(int callbackType,
Object action, Object token, long delayMillis) {
synchronized (mLock) {
final long now = SystemClock.uptimeMillis();
final long dueTime = now + delayMillis;
//添加callback到回调队列
mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);
if (dueTime <= now) {
scheduleFrameLocked(now);
} else {
//设定的执行时间在当前时间之后,发送MSG_DO_SCHEDULE_CALLBACK,由FrameHanlder安排执行scheduleFrameLocked
Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);
msg.arg1 = callbackType;
msg.setAsynchronous(true);
mHandler.sendMessageAtTime(msg, dueTime);`
}
}
}

scheduleFrameLocked

private void scheduleFrameLocked(long now) {

if (isRunningOnLooperThreadLocked()) {
//若当前线程是UI线程,执行scheduleVsyncLocked请求VSYNC信号
scheduleVsyncLocked();
} else {
//非UI线程,发送MSG_DO_SCHEDULE_VSYNC消息到主线程
Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC);
msg.setAsynchronous(true);
mHandler.sendMessageAtFrontOfQueue(msg);
}

}

scheduleVsyncLocked最终调用FrameDisplayEventReceiver#scheduleVsync,收到Vsync信息后,调用FrameDisplayEventReceiver#onVsync

FrameDisplayEventReceiver#onVsync

private final class FrameDisplayEventReceiver extends DisplayEventReceiver
implements Runnable {
private boolean mHavePendingVsync;
private long mTimestampNanos;
private int mFrame;

    public FrameDisplayEventReceiver(Looper looper) {
        super(looper);
    }

    @Override
    public void onVsync(long timestampNanos, int builtInDisplayId, int frame) {
        ....
        ....
        mTimestampNanos = timestampNanos;
        mFrame = frame;
        //该消息的callback为当前对象FrameDisplayEventReceiver,收到消息调用其run方法,然后调用doFrame方法
        Message msg = Message.obtain(mHandler, this);
        msg.setAsynchronous(true);
        mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
    }

    @Override
    public void run() {
        mHavePendingVsync = false;
        doFrame(mTimestampNanos, mFrame);
    }
}

doFrame

void doFrame(long frameTimeNanos, int frame) {
        ....
        //Vsync信号到来时间    
        long intendedFrameTimeNanos = frameTimeNanos;
        //实际开始执行当前frame的时间
        startNanos = System.nanoTime();
        //时间差
        final long jitterNanos = startNanos - frameTimeNanos;
        //时间差大于帧率,则认为是跳帧
        if (jitterNanos >= mFrameIntervalNanos) {
            final long skippedFrames = jitterNanos / mFrameIntervalNanos;
            if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) {
                Log.i(TAG, "Skipped " + skippedFrames + " frames!  "
                        + "The application may be doing too much work on its main thread.");
            }
          ....
          ....
         //记录当前frame信息   
        mFrameInfo.setVsync(intendedFrameTimeNanos, frameTimeNanos);
        mFrameScheduled = false;
          //记录上一次frame渲染的时间点
        mLastFrameTimeNanos = frameTimeNanos;
    }

    try {
        //执行CallBack,优先级为:CALLBACK_INPUT>CALLBACK_ANIMATION>CALLBACK_TRAVERSAL>CALLBACK_COMMIT
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Choreographer#doFrame");
        mFrameInfo.markInputHandlingStart();
        doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos);
        mFrameInfo.markAnimationsStart();
        doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos);
        mFrameInfo.markPerformTraversalsStart();
        doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
        doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
    ....
}

doCallbacks

void doCallbacks(int callbackType, long frameTimeNanos) {
    CallbackRecord callbacks;
    synchronized (mLock) {
        final long now = System.nanoTime();
        // 从队列查找相应类型的CallbackRecord对象
        callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked(
                now / TimeUtils.NANOS_PER_MS);
        if (callbacks == null) {
            return;
        }
        mCallbacksRunning = true;
      ....
      ....  
    try {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, CALLBACK_TRACE_TITLES[callbackType]);
        for (CallbackRecord c = callbacks; c != null; c = c.next) {
            ....
            //调用CallbackRecord的run方法
            c.run(frameTimeNanos);
        }
    } finally {
        synchronized (mLock) {
            mCallbacksRunning = false;
            //回收callbacks,加入mCallbackPool对象池
            do {
                final CallbackRecord next = callbacks.next;
                recycleCallbackLocked(callbacks);
                callbacks = next;
            } while (callbacks != null);
        }
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

CallbackRecord#run

public void run(long frameTimeNanos) {
if (token == FRAME_CALLBACK_TOKEN) {
//调用自定义FrameCallback的doFrame方法
((FrameCallback)action).doFrame(frameTimeNanos);
} else {
((Runnable)action).run();
}
}

至此,关于Choreographer的整个调用流程及其原理已经分析完成。至于系统某些调用,如View的invalidate,触发ViewRootImpl#scheduleTraversals,最终调用
Choreographer#postCallback(Choreographer.CALLBACK_TRAVERSAL,mTraversalRunnable, null);,只是明确了Callbac的类型以及回调处理Runnable而已,基本流程和自定义FrameCallback一样。
总结

尽量避免在执行动画或渲染操作之后在主线程执行操作,在之前或之后都应该尽量避免发送消息到主线程looper

既然自定义FrameCallback可以在下一个frame被渲染的时候会被回调,那我们是不是可以根据这个原理实现应用的帧率监听呢,答案是肯定的,下面是我的简单实现:

1.自定义FrameCallback:FPSFrameCallback

public class FPSFrameCallback implements Choreographer.FrameCallback {

  private static final String TAG = "FPS_TEST";
  private long mLastFrameTimeNanos = 0;
  private long mFrameIntervalNanos;

  public FPSFrameCallback(long lastFrameTimeNanos) {
      mLastFrameTimeNanos = lastFrameTimeNanos;
      mFrameIntervalNanos = (long)(1000000000 / 60.0);
  }

  @Override
  public void doFrame(long frameTimeNanos) {

      //初始化时间
      if (mLastFrameTimeNanos == 0) {
          mLastFrameTimeNanos = frameTimeNanos;
      }
      final long jitterNanos = frameTimeNanos - mLastFrameTimeNanos;
      if (jitterNanos >= mFrameIntervalNanos) {
          final long skippedFrames = jitterNanos / mFrameIntervalNanos;
          if(skippedFrames>30){
              Log.i(TAG, "Skipped " + skippedFrames + " frames!  "
                      + "The application may be doing too much work on its main thread.");
          }
      }
      mLastFrameTimeNanos=frameTimeNanos;
      //注册下一帧回调
      Choreographer.getInstance().postFrameCallback(this);
  }

}

2.在Application中注册

  @Override
     public void onCreate() {
         super.onCreate();
         Choreographer.getInstance().postFrameCallback(new FPSFrameCallback(System.nanoTime()));
     }

3.测试

 public class MainActivity extends FragmentActivity {

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

     }

     @Override
     protected void onResume() {
         super.onResume();
         try {
             Thread.sleep(1000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
 }

LOG输出如下:

 I/Choreographer: Skipped 64 frames!  The application may be doing too much work on its main thread.
 I/FPS_TEST: Skipped 65 frames!  The application may be doing too much work on its main thread.

基本和系统监控数值一致

你可能感兴趣的:(performence)