当前位置:   article > 正文

ExoPlayer源码浅析(转载)

exoplayer源码

原文地址:https://www.jianshu.com/p/4dede867739d

ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates.

首先看看ExoPlayer类之间的继承关系,对这个框架有一个大致的印象

 

基本类图(不完整).png

ExoPlayer被定义为Interface,然后又几个内部类:Factory,Listener,其中,Factory负责初始化ExoPlayer的操作,其关键代码如下:

 

public static ExoPlayer newInstance(int rendererCount, int minBufferMs, int minRebufferMs) {  return new ExoPlayerImpl(rendererCount, minBufferMs, minRebufferMs);}

Listener则负责向外界回调ExoPlayer状态变化和错误信息。

ExoPlayer有一个子类:ExoPlayerImpl,它继承了ExoPlayer的所有方法,并且负责接收转发外界传递的消息,为什么是转发,不是接收呢?因为真正干活的不是ExoPlayerImpl,而是另外一个隐藏类,ExoPlayerImplInternal,几乎所有的操作都是在ExoPlayerImplInternal中完成的。

Start

我们看一个官方的使用Demo:

 

  1. // 1. Instantiate the player.
  2. player = ExoPlayer.Factory.newInstance(RENDERER_COUNT);
  3. // 2. Construct renderers.
  4. MediaCodecVideoTrackRenderer videoRenderer = ...
  5. MediaCodecAudioTrackRenderer audioRenderer = ...
  6. // 3. Inject the renderers through prepare.
  7. player.prepare(videoRenderer, audioRenderer);
  8. // 4. Pass the surface to the video renderer.
  9. player.sendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface);
  10. // 5. Start playback.
  11. player.setPlayWhenReady(true);
  12. ...
  13. player.release();
  14. // Don’t forget to release when done!

我们下面的探索过程都是按照这个Demo一步一步进行的

1.Instantiate the player.

首先,用户调用ExoPlayer.Factory.newInstance(...)方法得到ExoPlayerImpl的实例,这个过程中,我们看看做了什么:

 

  1. public ExoPlayerImpl(int rendererCount, int minBufferMs, int minRebufferMs) {
  2. Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION);
  3. //首先初始化一些状态
  4. this.playWhenReady = false;
  5. this.playbackState = STATE_IDLE;
  6. //ExoPlayer的Listener是通过andListener(listener:Listener)方法添加的,所以需要一个数组去记录所有的Listener
  7. this.listeners = new CopyOnWriteArraySet<>();
  8. //初始化轨道格式数组
  9. this.trackFormats = new MediaFormat[rendererCount][];
  10. //选中的轨道索引
  11. this.selectedTrackIndices = new int[rendererCount];
  12. //初始化一个Handler,并将收到的消息传递给ExoPlayerImpl的handleEvent()方法处理
  13. eventHandler = new Handler() {
  14. @Override
  15. public void handleMessage(Message msg) {
  16. ExoPlayerImpl.this.handleEvent(msg);
  17. }
  18. };
  19. //初始化ExoPlayerImplInternal
  20. internalPlayer = new ExoPlayerImplInternal(eventHandler, playWhenReady, selectedTrackIndices,
  21. minBufferMs, minRebufferMs);
  22. }

然后我们继续看ExoPlayerImplInternal的构造方法:

 

  1. public ExoPlayerImplInternal(Handler eventHandler, boolean playWhenReady,int[] selectedTrackIndices, int minBufferMs, int minRebufferMs) {
  2. //接受从ExoPlayerImpl传递进来的Handler
  3. this.eventHandler = eventHandler;
  4. //初始化
  5. this.playWhenReady = playWhenReady;
  6. this.minBufferUs = minBufferMs * 1000L;
  7. this.minRebufferUs = minRebufferMs * 1000L;
  8. //拷贝
  9. this.selectedTrackIndices = Arrays.copyOf(selectedTrackIndices, selectedTrackIndices.length);
  10. this.state = ExoPlayer.STATE_IDLE;
  11. this.durationUs = TrackRenderer.UNKNOWN_TIME_US;
  12. this.bufferedPositionUs = TrackRenderer.UNKNOWN_TIME_US;
  13. //初始化StandaloneMediaClock类,它是一个时钟类,原理是通过获取手机启动时间进行差值计算
  14. standaloneMediaClock = new StandaloneMediaClock();
  15. //初始化一个自增Integer
  16. pendingSeekCount = new AtomicInteger();
  17. enabledRenderers = new ArrayList<TrackRenderer>(selectedTrackIndices.length);
  18. trackFormats = new MediaFormat[selectedTrackIndices.length][];
  19. // Note: The documentation for Process.THREAD_PRIORITY_AUDIO that states "Applications can
  20. // not normally change to this priority" is incorrect.
  21. //初始化和启动一个HandlerThread
  22. internalPlaybackThread = new PriorityHandlerThread("ExoPlayerImplInternal:Handler",Process.THREAD_PRIORITY_AUDIO);
  23. internalPlaybackThread.start();
  24. //为HandlerThread添加一个Handler
  25. handler = new Handler(internalPlaybackThread.getLooper(), this);
  26. }

至此,ExoPlayerImpl和ExoPlayerImplInternal两个类的状态都被初始化,启动一个Process.THREAD_PRIORITY_AUDIO的线程,准备接受任务。

2.Construct renderers.

ExoPlayer被初始化后,用户需要调用ExoPlayer.prepare(...)进行准备工作:

 

public void prepare(TrackRenderer... renderers);

TrackRenderer和它的孩子们

我们看到,prepare形参是TrackRenderer数组,那么这个TrackRenderer是个什么东东呢?

ExoPlayer的媒体组件,都是通过注入的方式实现的,而TrackRenderer就是媒体组件的基类。

 

public abstract class TrackRenderer implements ExoPlayerComponent {}

源码看,TrackRenderer是个抽象类,继承自ExoPlayerComponent,只有一个属性:

 

private int state;

大部分方法都是围绕state实现的,剩下的都是抽象方法,TrackRenderer类用来维护state,而具体的工作需要子类去实现,而做法比较巧妙,如TrackRenderer的prepare()方法:

 

  1. //prepare方法维护state属性的状态,具体的执行则是调用doPrepare()方法
  2. final int prepare(long positionUs) throws ExoPlaybackException {
  3. Assertions.checkState(state == STATE_UNPREPARED);
  4. state = doPrepare(positionUs) ? STATE_PREPARED : STATE_UNPREPARED;
  5. return state;
  6. }
  7. //抽象方法,由子类实现
  8. protected abstract boolean doPrepare(long positionUs) throws ExoPlaybackException;

再看看ExoPlayerComponent

 

  1. public interface ExoPlayerComponent {
  2. void handleMessage(int messageType, Object message) throws ExoPlaybackException;
  3. }

从名字看,它是一个组件,用于在播放线程接受消息,所有实现它的类都可以在播放线程接受消息,所以TrackRenderer可以接收来自其他线程的消息。

那我们看TrackRenderer有哪些子类

 

TrackRenderer.png

从类图来看,TrackRenderer有很多子类,其中,SampleSourceTrackRenderer比较重要,我们看一下官方文档对这个类的介绍:

 

SampleSourceTrackRenderer.png

SampleSource and SampleSourceReader

TrackRenderer的实例,渲染来从SampleSource采集的样本,SampleSource是什么呢,从名字看应该是样本源:

 

 

SampleSource.png

媒体样本源,SampleSource一般暴漏一个或多个轨道,轨道的个数和每个轨道的格式可以通过 SampleSource.SampleSourceReader.getTrackCount()和SampleSource.SampleSourceReader.getFormat(int)得到。

再回头看SampleSourceTrackRenderer的构造方法:

 

  1. public SampleSourceTrackRenderer(SampleSource... sources) {
  2. this.sources = new SampleSourceReader[sources.length];
  3. for (int i = 0; i < sources.length; i++) {
  4. this.sources[i] = sources[i].register();
  5. }
  6. }

接受一个或者多个SampleSource数组,然后调用了SampleSource的register()方法

 

  1. /**
  2. * A consumer of samples should call this method to register themselves and gain access to the
  3. * source through the returned {@link SampleSourceReader}.
  4. * <p>
  5. * {@link SampleSourceReader#release()} should be called on the returned object when access is no
  6. * longer required.
  7. *
  8. * @return A {@link SampleSourceReader} that provides access to the source.
  9. */
  10. public SampleSourceReader register();

从官方介绍来看,消费者(获取样本的类,这里是指SampleSourceTrackRenderer)通过调用register()方法来获得对媒体样本读取的能力。

register()方法返回SampleSourceReader类:

 

  1. /**
  2. *An interface providing read access to a {@link SampleSource}.
  3. */
  4. public interface SampleSourceReader

是一个接口,定义了一些访问媒体样本的方法,以下列举一些重要的方法,详细可以去com.google.android.exoplayer.SampleSource.SampleSourceReader类查看:

  • prepare(long positionUS):boolean
  • getTrackCount():int
  • getFormat(int track):MediaFormat
  • enable(int track,long position)
  • disable(int track)
  • readData(int track,long positionUs,MediaFormatHolder formatHolder,SampleHolder sampleHolder):int
  • seekToUs(long positionUs)
  • release()

继续看SampleSourceTrackRenderer的构造方法:

 

this.sources[i] = sources[i].register();

SampleSourceTrackRenderer中定义一个全局变量,存储所有的SampleSourceReader,方便其他方法访问SampleSource中的资源。

到这里,ExoPlayer的框架结构就比较清晰了,TrackRenderer负责渲染由SampleSource提供的媒体样本。

3. Inject the renderers through prepare.

 

player.prepare(videoRenderer, audioRenderer);

前两步分别初始化ExoPlayer、TrackRenderer和SampleSource,并将SampleSource注入到TrackRenderer,但是直到现在,TrackRenderer都没有和ExoPlayer产生关系,客官们是不是等的不耐烦了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/295761
推荐阅读
相关标签