ExoPlayer的缓存 – 三 Cache的使用

CacheDataSource 读取数据
创建 CacheDataSource
和 exoplayer 的其他 DataSource 一样,CacheDataSource 的生成也是通过 Factory 模式生成,
private CacheDataSource createDataSourceInternal(
@Nullable DataSource upstreamDataSource, @Flags int flags, int upstreamPriority) {
Cache cache = checkNotNull(this.cache);
@Nullable DataSink cacheWriteDataSink;
if (cacheIsReadOnly || upstreamDataSource == null) {
cacheWriteDataSink = null;
} else if (cacheWriteDataSinkFactory != null) {
cacheWriteDataSink = cacheWriteDataSinkFactory.createDataSink();
} else {
cacheWriteDataSink = new CacheDataSink.Factory().setCache(cache).createDataSink();
}
return new CacheDataSource(
cache,
upstreamDataSource,
cacheReadDataSourceFactory.createDataSource(),
cacheWriteDataSink,
cacheKeyFactory,
flags,
upstreamPriorityTaskManager,
upstreamPriority,
eventListener);
}
}
CacheDataSource 构造函数的参数和读写有关的有
-
Cache cache 使用的缓存
-
@Nullable DataSource upstreamDataSource 根据url 生成的 DataSource, 可为null, 只能从Cache 中读取数据
-
cacheReadDataSource 从cache 中读取数据用的 DataSource
-
@Nullable DataSink cacheWriteDataSink 写缓存用的DataSink,可为null, 不可向Cache 中写数据
-
@Nullable CacheKeyFactory cacheKeyFactory 用来生成 Cache ID, 用来匹配Cache
private CacheDataSource(
Cache cache,
@Nullable DataSource upstreamDataSource,
DataSource cacheReadDataSource,
@Nullable DataSink cacheWriteDataSink,
@Nullable CacheKeyFactory cacheKeyFactory,
......
) {
......
this.upstreamDataSource = upstreamDataSource;
this.cacheWriteDataSource =
cacheWriteDataSink != null
? new TeeDataSource(upstreamDataSource, cacheWriteDataSink)
: null;
}
在 CacheDataSource 的构造函数中 通过 upstreamDataSource 和cacheWriteDataSink 生成cacheWriteDataSource 类型为TeeDataSource。 缓存的保存正是通过TeeDataSource 完成。
TeeDataSource 写入缓存数据
在TeeDataSource 的read 函数中,先从upstream 中 读取数据,然后写入到dataSink 中。
public int read(byte[] buffer, int offset, int length) throws IOException {
if (bytesRemaining == 0) {
return C.RESULT_END_OF_INPUT;
}
int bytesRead = upstream.read(buffer