图片框架 - Glide加载webp动图流程解析

一、客户端代码介绍

这里分两个部分:

1)添加webp动图解码组件
@GlideModule
public class WebpGlideLibraryModule extends LibraryGlideModule {

    @Override
   public void registerComponents(Context context, Glide glide, Registry registry) {
       final BitmapPool bitmapPool = glide.getBitmapPool();
       final ArrayPool arrayPool = glide.getArrayPool();
       /* animate webp decoders */
      ByteBufferWebpDecoder byteBufferWebpDecoder = new ByteBufferWebpDecoder(context, arrayPool, bitmapPool);
...
       /* Animated webp images */
       registry.prepend(InputStream.class, WebpDrawable.class, new StreamWebpDecoder(byteBufferWebpDecoder, arrayPool))
...
   }
}

ByteBufferWebpDecoder是最终webp动图资源解码器

2)Glide加载webp动图url
Glide.with(mContext).load(Constants.dynamicWebpUrl).into(mImageView);

二、Glide加载网络webp数据转换流程

先给出Glide加载webp动图的完整调用栈:

    com.bumptech.glide.integration.webp.decoder.ByteBufferWebpDecoder.decode:33
    com.bumptech.glide.load.engine.DecodePath.decodeResourceWithList:72
    com.bumptech.glide.load.engine.DecodePath.decodeResource:55
    com.bumptech.glide.load.engine.DecodePath.decode:45
    com.bumptech.glide.load.engine.LoadPath.loadWithExceptionList:62
    com.bumptech.glide.load.engine.LoadPath.load:47
    com.bumptech.glide.load.engine.DecodeJob.runLoadPath:510
    com.bumptech.glide.load.engine.DecodeJob.decodeFromFetcher:475
    com.bumptech.glide.load.engine.DecodeJob.decodeFromData:461
    com.bumptech.glide.load.engine.DecodeJob.decodeFromRetrievedData:413
    com.bumptech.glide.load.engine.DecodeJob.onDataFetcherReady:382
    com.bumptech.glide.load.engine.SourceGenerator.onDataFetcherReady:139
    com.bumptech.glide.load.engine.DataCacheGenerator.onDataReady:99
    com.bumptech.glide.load.model.ByteBufferFileLoader$ByteBufferFetcher.loadData:74
    com.bumptech.glide.load.engine.DataCacheGenerator.startNext:79
    com.bumptech.glide.load.engine.SourceGenerator.startNext:53
    com.bumptech.glide.load.engine.DecodeJob.runGenerators:305
    com.bumptech.glide.load.engine.DecodeJob.runWrapped:275

    com.bumptech.glide.load.engine.DecodeJob.run:236
    java.util.concurrent.ThreadPoolExecutor.runWorker:1167
    java.util.concurrent.ThreadPoolExecutor$Worker.run:641
    com.bumptech.glide.load.engine.EngineJob.start:118
    com.bumptech.glide.load.engine.Engine.load:233
    com.bumptech.glide.request.SingleRequest.onSizeReady:432
    com.bumptech.glide.request.target.ViewTarget$SizeDeterminer.getSize:389
    com.bumptech.glide.request.target.ViewTarget.getSize:221
    com.bumptech.glide.request.SingleRequest.begin:257
    com.bumptech.glide.manager.RequestTracker.runRequest:44
    com.bumptech.glide.RequestManager.track:616
    com.bumptech.glide.RequestBuilder.into:651
    com.bumptech.glide.RequestBuilder.into:711

整个流程主要分三块:

  • 封装并发起一个图片加载Request
  • 图片资源获取:内存缓存、磁盘文件缓存、网络请求等。
  • 图片资源解析:对某些数据源进行资源解码。
2.1 封装并发起一个图片加载Request

load :通过RequestManager加载一个String 类型的model。
into:加载一个ImageView的目标控件作为target,然后通过RequestBuilder开始数据处理流程。

2.2 图片资源获取

EngineJob以前的流程非常简单明确,这里着重看下DecodeJob部分的处理流程:

SourceGenerator.java

@Override
public boolean startNext() {
  if (dataToCache != null) {
    Object data = dataToCache;
   dataToCache = null;
   cacheData(data);
  }

  if (sourceCacheGenerator != null && sourceCacheGenerator.startNext()) {
    return true;
  }

  sourceCacheGenerator = null;
  loadData = null;
  boolean started = false;
  while (!started && hasNextModelLoader()) {
    loadData = helper.getLoadData().get(loadDataListIndex++);
   if (loadData != null
       && (helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.getDataSource())
        || helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
      started = true;
     loadData.fetcher.loadData(helper.getPriority(), this);
   }
  }
  return started;
}

这里有个ModelLoader-LoadData-DataFetcher关系需要捋一下:

DecodeHelper.java

List<LoadData<?>> getLoadData() {
  if (!isLoadDataSet) {
    isLoadDataSet = true;
   loadData.clear();
   List<ModelLoader<Object, ?>> modelLoaders = glideContext.getRegistry().getModelLoaders(model);
   //noinspection ForLoopReplaceableByForEach to improve perf
   for (int i = 0, size = modelLoaders.size(); i < size; i++) {
      ModelLoader<Object, ?> modelLoader = modelLoaders.get(i);
     LoadData<?> current =
          modelLoader.buildLoadData(model, width, height, options);
     if (current != null) {
        loadData.add(current);
     }
    }
  }
  return loadData;
}

这里modelLoaders是在Registry中由ModelLoaderRegistry来获取所有的models。这里model对应ByteBufferFileLoader,由他执行buildLoadData。

ByteBufferFileLoader.java

@Override
public LoadData<ByteBuffer> buildLoadData(@NonNull File file, int width, int height,
   @NonNull Options options) {
  return new LoadData<>(new ObjectKey(file), new ByteBufferFetcher(file));
}

而LoadData是ModelLoader的内部类,它的属性包括一个DataFetcher,它就是最终加载数据的地方。

class LoadData<Data> {
  public final Key sourceKey;
  public final List<Key> alternateKeys;
  public final DataFetcher<Data> fetcher;
...
}

那么总结一下:首先是获取对应数据源类型的ModelLoader,ModelLoader初始化一个LoadData,然后LoadData通过内部关联的DataFetcher来正真去执行加载数据的操作!

这里很显然对应的DataFetcher实例是LoadData初始化时传入的ByteBufferFetcher。回到SourceGenerator的startNext方法,最终调用ByteBufferFetcher的loadData。

当然这里数据获取的方式有很多种,有网络请求、有磁盘文件获取等等:

DataFetcher子类

这里DataFetcher也可以自定义,举例:
Glide网络请求默认使用的是HttpUrlConnection,这里可以替换为Okhttp请求。
做法是:

public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
  private final Call.Factory client;
  // Public API.
  @SuppressWarnings("WeakerAccess")
  public OkHttpUrlLoader(@NonNull Call.Factory client) {
    this.client = client;
  }

  @Override
  public boolean handles(@NonNull GlideUrl url) {
    return true;
  }

  @Override
  public LoadData<InputStream> buildLoadData(@NonNull GlideUrl model, int width, int height,
     @NonNull Options options) {
    return new LoadData<>(model, new OkHttpStreamFetcher(client, model));
  }
...
}

创建对应的ModelLoader,并且自定义一个OkHttpStreamFetcher来实现Okhttp网络请求功能,同时通过Registry去替换组件:

@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}

这里基本上图片资源获取就介绍完了。

2.3 图片资源解析

资源获取成功后,会通过callback.onDataReady(result)进行回调,这个callback是通过参数传入的loadData.fetcher.loadData(helper.getPriority(), this),这里的this就是SourceGenerator

SourceGenerator.java

@Override
public void onDataReady(Object data) {
  DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
  if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
    dataToCache = data;
   // We might be being called back on someone else's thread. Before doing anything, we should
   // reschedule to get back onto Glide's thread.
   cb.reschedule();
  } else {
    cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
       loadData.fetcher.getDataSource(), originalKey);
  }
}

这个cb是FetcherReadyCallback,在SourceGenerator初始化时传入

SourceGenerator(DecodeHelper<?> helper, FetcherReadyCallback cb) {
  this.helper = helper;
  this.cb = cb;
}

从SourceGenerator初始化出追这个cb,就是DecodeJob,这样最终获取的数据源通过两层callback传入了DecodeJob,准备进行解码处理。

DecodeJob.java
onDataFetcherReady() -> decodeFromRetrievedData() ->decodeFromData()->decodeFromFetcher()
这个流程没什么可分析的,直接到decodeFromFetcher

private <Data> Resource<R> decodeFromFetcher(Data data, DataSource dataSource)
    throws GlideException {
  LoadPath<Data, ?, R> path = decodeHelper.getLoadPath((Class<Data>) data.getClass());
  return runLoadPath(data, dataSource, path);
}

DecodeHelper.java

<Data> LoadPath<Data, ?, Transcode> getLoadPath(Class<Data> dataClass) {
  return glideContext.getRegistry().getLoadPath(dataClass, resourceClass, transcodeClass);
}

这里很显然又是去Registry拿的。如果有的话最终会返回一个LoadPath对象

new LoadPath<>(dataClass, resourceClass, transcodeClass, decodePaths, throwableListPool);

继续往下走:

private <Data, ResourceType> Resource<R> runLoadPath(Data data, DataSource dataSource,
   LoadPath<Data, ResourceType, R> path) throws GlideException {
  Options options = getOptionsWithHardwareConfig(dataSource);
  DataRewinder<Data> rewinder = glideContext.getRegistry().getRewinder(data);
  try {
    // ResourceType in DecodeCallback below is required for compilation to work with gradle.
   return path.load(
        rewinder, options, width, height, new DecodeCallback<ResourceType>(dataSource));
  } finally {
    rewinder.cleanup();
  }
}

这里调用LoadPath的load方法,该方法调用loadWithExceptionList

LoadPath.java

private Resource<Transcode> loadWithExceptionList(DataRewinder<Data> rewinder,
   @NonNull Options options,
   int width, int height, DecodePath.DecodeCallback<ResourceType> decodeCallback,
   List<Throwable> exceptions) throws GlideException {
  Resource<Transcode> result = null;
  //noinspection ForLoopReplaceableByForEach to improve perf
  for (int i = 0, size = decodePaths.size(); i < size; i++) {
    DecodePath<Data, ResourceType, Transcode> path = decodePaths.get(i);
   try {
      result = path.decode(rewinder, width, height, options, decodeCallback);
   } catch (GlideException e) {
      exceptions.add(e);
   }

    if (result != null) {
      break;
   }
  }

  if (result == null) {
    throw new GlideException(failureMessage, new ArrayList<>(exceptions));
  }
  return result;
}

这里获取了一个decodePath,然后调用它的decode方法去执行具体的解码工作了。debug一个看看这里path是什么

这里就是文章开头说的客户端自定义添加webp动图解码组件。具体解码处理留到下一篇分析。

好的,最后再来简单总结下整个流程:

上层Glide作为客户端调用的主入口,通过RequestManager以及RequestBuilder收集图片源model以及目标控件target,创建一个对应的request交给EngineJob线程池去处理这个request,DecodeJob作为一个执行线程接收这个request任务,然后交由Generator选择处理方式,包括缓存还是网络请求等,而它通过获取Registry注册的对应的ModelLoader-LoadData-DataFetcher最终去获取图片数据。然后由Generator回调给DecodeJob,DecodeJob通过向Registry获取对应的LoadPath,最终匹配到对应的解码器DecodePath去执行解码操作。

后面就是将通过onSourceReady层层回调返回到SingleRequest,最终为目标控件设置webp动图资源。


整个数据转换流程为:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355