Android视频点播的实现代码(边播边缓存)

Android视频点播的实现代码(边播边缓存),第1张

概述简述一些知名的视频app客户端(优酷,爱奇艺)播放视频的时候都有一些缓存进度(二级进度缓存),还有一些短视频app,都有边播边缓的处理。还有就是当文件缓存完毕了再次播放的话就不再请求网络了直接播放本地文件了。

简述

一些知名的视频app客户端(优酷,爱奇艺)播放视频的时候都有一些缓存进度(二级进度缓存),还有一些短视频app,都有边播边缓的处理。还有就是当文件缓存完毕了再次播放的话就不再请求网络了直接播放本地文件了。既节省了流程又提高了加载速度。
今天我们就是来研究讨论实现这个边播边缓存的框架,因为它不和任何的业务逻辑耦合。

开源的项目

目前比较好的开源项目是:https://github.com/danikula/AndroidVideoCache

代码的架构写的也很不错,网络用的httpurlconnect,文件缓存处理,文件最大限度策略,回调监听处理,断点续传,代理服务等。很值得研究阅读.

个人觉得项目中有几个需要优化的点,今天就来处理这几个并简要分析下原理

优化点比如:

文件的缓存超过限制后没有按照lru算法删除, 处理返回给播放器的http响应头消息,响应头消息的获取处理改为head请求(需服务器支持) 替换网络库为okhttp(因为大部分的项目都是以okhttp为网络请求库的)

该开源项目的原理分析-本地代理


采用了本地代理服务的方式,通过原始url给播放器返回一个本地代理的一个url ,代理URL类似:http://127.0.0.1:57430/xxxx;然后播放器播放的时候请求到了你本地的代理上了。 本地代理采用ServerSocket监听127.0.0.1的有效端口,这个时候手机就是一个服务器了,客户端就是socket,也就是播放器。 读取客户端就是socket来读取数据(http协议请求)解析http协议。 根据url检查视频文件是否存在,读取文件数据给播放器,也就是往socket里写入数据。同时如果没有下载完成会进行断点下载,当然弱网的话数据需要生产消费同步处理。

优化点

1. 文件的缓存超过限制后没有按照lru算法删除.

files类。

由于在移动设备上file.setLastModifIEd() 方法不支持毫秒级的时间处理,导致超出限制大小后本应该删除老的,却没有删除抛出了异常。注释掉主动抛出的异常即可。因为文件的修改时间就是对的。

  static voID setLastModifIEdNow(file file) throws IOException {    if (file.exists()) {      long Now = System.currentTimeMillis();      boolean modifIEd = file.setLastModifIEd(Now/1000*1000); // on some devices (e.g. Nexus 5) doesn't work      if (!modifIEd) {        modify(file);//        if (file.lastModifIEd() < Now) {//          VIDeoCacheLog.deBUG("LrudiskUsage","modifIEd not ok ");//          throw new IOException("Error set last modifIEd date to " + file);//        }else{//          VIDeoCacheLog.deBUG("LrudiskUsage","modifIEd ok ");//        }      }    }  }

2. 处理返回给播放器的http响应头消息,响应头消息的获取处理改为head请求(需要服务器支持)

httpUrlSource类。fetchContentInfo方法是获取视频文件的Content-Type,Content-Length信息,是为了播放器播放的时候给播放器组装http响应头信息用的。所以这一块需要用数据库保存,这样播放器每次播放的时候不要在此获取了,减少了请求的次数,节省了流量。既然是只需要头信息,不需要响应体,所以我们在获取的时候可以直接采用head方法。所以代码增加了一个方法openConnectionForheader如下:

 private voID fetchContentInfo() throws ProxyCacheException {    VIDeoCacheLog.deBUG(TAG,"Read content info from " + sourceInfo.url);    httpURLConnection urlConnection = null;    inputStream inputStream = null;    try {      urlConnection = openConnectionForheader(20000);      long length = getContentLength(urlConnection);      String mime = urlConnection.getContentType();      inputStream = urlConnection.getinputStream();      this.sourceInfo = new SourceInfo(sourceInfo.url,length,mime);      this.sourceInfoStorage.put(sourceInfo.url,sourceInfo);      VIDeoCacheLog.deBUG(TAG,"Source info fetched: " + sourceInfo);    } catch (IOException e) {      VIDeoCacheLog.error(TAG,"Error fetching info from " + sourceInfo.url,e);    } finally {      ProxyCacheUtils.close(inputStream);      if (urlConnection != null) {        urlConnection.disconnect();      }    }  }  // for head  private httpURLConnection openConnectionForheader(int timeout) throws IOException,ProxyCacheException {    httpURLConnection connection;    boolean redirected;    int redirectCount = 0;    String url = this.sourceInfo.url;    do {      VIDeoCacheLog.deBUG(TAG,"Open connection for header to " + url);      connection = (httpURLConnection) new URL(url).openConnection();      if (timeout > 0) {        connection.setConnectTimeout(timeout);        connection.setReadTimeout(timeout);      }      //只返回头部,不需要BODY,既可以提高响应速度也可以减少网络流量      connection.setRequestMethod("head");      int code = connection.getResponseCode();      redirected = code == http_MOVED_PERM || code == http_MOVED_TEMP || code == http_SEE_OTHER;      if (redirected) {        url = connection.getheaderFIEld("Location");        VIDeoCacheLog.deBUG(TAG,"Redirect to:" + url);        redirectCount++;        connection.disconnect();        VIDeoCacheLog.deBUG(TAG,"Redirect closed:" + url);      }      if (redirectCount > MAX_REDIRECTS) {        throw new ProxyCacheException("Too many redirects: " + redirectCount);      }    } while (redirected);    return connection;  }

3.替换网络库为okhttp(因为大部分的项目都是以okhttp为网络请求库的)

为什么我们要换呢?!一是OKhttp是一款高效的http客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的Gzip压缩,请求缓存等优势,其核心主要有路由、连接协议、拦截器、代理、安全性认证、连接池以及网络适配,拦截器主要是指添加,移除或者转换请求或者回应的头部信息。得到了androID开发的认可。二是大部分的app都是采用OKhttp,而且Google会将其纳入androID 源码中。三是该作者代码中用的httpurlconnet在httpUrlSource有这么一段:

 @OverrIDe  public voID close() throws ProxyCacheException {    if (connection != null) {      try {        connection.disconnect();      } catch (NullPointerException | IllegalArgumentException e) {        String message = "Wait... but why? WTF!? " +            "Really shouldn't happen any more after fixing https://github.com/danikula/AndroIDVIDeoCache/issues/43. " +            "If you read it on your device log,please,notify me danikula@gmail.com or create issue here " +            "https://github.com/danikula/AndroIDVIDeoCache/issues.";        throw new RuntimeException(message,e);      } catch (Arrayindexoutofboundsexception e) {        VIDeoCacheLog.error(TAG,"Error closing connection correctly. Should happen only on AndroID L. " +            "If anybody kNow how to fix it,please visit https://github.com/danikula/AndroIDVIDeoCache/issues/88. " +            "Until good solution is not kNow,just ignore this issue :(",e);      }    }  }

在没有像okhttp这些优秀的网络开源项目之前,androID开发都是采用httpurlconnet或者httpclIEnt,部分手机可能会遇到这个问题哈。

这里采用的 compile 'com.squareup.okhttp:okhttp:2.7.5' 版本的来实现该类的功能。在原作者的架构思路上我们只需要增加实现Source接口的类OkhttpUrlSource即可,可见作者的代码架构还是不错的,当然我们同样需要处理上文中提高的优化点2中的问题。将项目中所有用到httpUrlSource的地方改为OkhttpUrlSource即可。
源码如下:

/** * ================================================ * 作  者:顾修忠 * 版  本: * 创建日期:2017/4/13-上午12:03 * 描  述:在一些AndroID手机上httpURLConnection.disconnect()方法仍然耗时太久, * 进行导致MediaPlayer要等待很久才会开始播放,因此决定使用okhttp替换httpURLConnection */public class OkhttpUrlSource implements Source {  private static final String TAG = OkhttpUrlSource.class.getSimplename();  private static final int MAX_REDIRECTS = 5;  private final SourceInfoStorage sourceInfoStorage;  private SourceInfo sourceInfo;  private OkhttpClIEnt okhttpClIEnt = new OkhttpClIEnt();  private Call requestCall = null;  private inputStream inputStream;  public OkhttpUrlSource(String url) {    this(url,SourceInfoStorageFactory.newEmptySourceInfoStorage());  }  public OkhttpUrlSource(String url,SourceInfoStorage sourceInfoStorage) {    this.sourceInfoStorage = checkNotNull(sourceInfoStorage);    SourceInfo sourceInfo = sourceInfoStorage.get(url);    this.sourceInfo = sourceInfo != null ? sourceInfo :        new SourceInfo(url,Integer.MIN_VALUE,ProxyCacheUtils.getSupposablyMime(url));  }  public OkhttpUrlSource(OkhttpUrlSource source) {    this.sourceInfo = source.sourceInfo;    this.sourceInfoStorage = source.sourceInfoStorage;  }  @OverrIDe  public synchronized long length() throws ProxyCacheException {    if (sourceInfo.length == Integer.MIN_VALUE) {      fetchContentInfo();    }    return sourceInfo.length;  }  @OverrIDe  public voID open(long offset) throws ProxyCacheException {    try {      Response response = openConnection(offset,-1);      String mime = response.header("Content-Type");      this.inputStream = new BufferedinputStream(response.body().byteStream(),DEFAulT_BUFFER_SIZE);      long length = readSourceAvailableBytes(response,offset,response.code());      this.sourceInfo = new SourceInfo(sourceInfo.url,sourceInfo);    } catch (IOException e) {      throw new ProxyCacheException("Error opening okhttpClIEnt for " + sourceInfo.url + " with offset " + offset,e);    }  }  private long readSourceAvailableBytes(Response response,long offset,int responseCode) throws IOException {    long contentLength = getContentLength(response);    return responseCode == http_OK ? contentLength        : responseCode == http_PARTIAL ? contentLength + offset : sourceInfo.length;  }  private long getContentLength(Response response) {    String contentLengthValue = response.header("Content-Length");    return contentLengthValue == null ? -1 : Long.parseLong(contentLengthValue);  }  @OverrIDe  public voID close() throws ProxyCacheException {    if (okhttpClIEnt != null && inputStream != null && requestCall != null) {      try {        inputStream.close();        requestCall.cancel();      } catch (IOException e) {        e.@R_404_1715@();        throw new RuntimeException(e.getMessage(),e);      }    }  }  @OverrIDe  public int read(byte[] buffer) throws ProxyCacheException {    if (inputStream == null) {      throw new ProxyCacheException("Error reading data from " + sourceInfo.url + ": okhttpClIEnt is absent!");    }    try {      return inputStream.read(buffer,buffer.length);    } catch (InterruptedioException e) {      throw new InterruptedProxyCacheException("Reading source " + sourceInfo.url + " is interrupted",e);    } catch (IOException e) {      throw new ProxyCacheException("Error reading data from " + sourceInfo.url,e);    }  }  private voID fetchContentInfo() throws ProxyCacheException {    VIDeoCacheLog.deBUG(TAG,"Read content info from " + sourceInfo.url);    Response response = null;    inputStream inputStream = null;    try {      response = openConnectionForheader(20000);      if (response == null || !response.isSuccessful()) {        throw new ProxyCacheException("Fail to fetchContentInfo: " + sourceInfo.url);      }      long length = getContentLength(response);      String mime = response.header("Content-Type","application/mp4");      inputStream = response.body().byteStream();      this.sourceInfo = new SourceInfo(sourceInfo.url,sourceInfo);      VIDeoCacheLog.info(TAG,"Content info for `" + sourceInfo.url + "`: mime: " + mime + ",content-length: " + length);    } catch (IOException e) {      VIDeoCacheLog.error(TAG,e);    } finally {      ProxyCacheUtils.close(inputStream);      if (response != null && requestCall != null) {        requestCall.cancel();      }    }  }  // for head  private Response openConnectionForheader(int timeout) throws IOException,ProxyCacheException {    if (timeout > 0) {//      okhttpClIEnt.setConnectTimeout(timeout,TimeUnit.MILliSECONDS);//      okhttpClIEnt.setReadTimeout(timeout,TimeUnit.MILliSECONDS);//      okhttpClIEnt.setWriteTimeout(timeout,TimeUnit.MILliSECONDS);    }    Response response;    boolean isRedirect = false;    String newUrl = this.sourceInfo.url;    int redirectCount = 0;    do {      //只返回头部,不需要BODY,既可以提高响应速度也可以减少网络流量      Request request = new Request.Builder()          .head()          .url(newUrl)          .build();      requestCall = okhttpClIEnt.newCall(request);      response = requestCall.execute();      if (response.isRedirect()) {        newUrl = response.header("Location");        VIDeoCacheLog.deBUG(TAG,"Redirect to:" + newUrl);        isRedirect = response.isRedirect();        redirectCount++;        requestCall.cancel();        VIDeoCacheLog.deBUG(TAG,"Redirect closed:" + newUrl);      }      if (redirectCount > MAX_REDIRECTS) {        throw new ProxyCacheException("Too many redirects: " + redirectCount);      }    } while (isRedirect);    return response;  }  private Response openConnection(long offset,int timeout) throws IOException,TimeUnit.MILliSECONDS);    }    Response response;    boolean isRedirect = false;    String newUrl = this.sourceInfo.url;    int redirectCount = 0;    do {      VIDeoCacheLog.deBUG(TAG,"Open connection" + (offset > 0 ? " with offset " + offset : "") + " to " + sourceInfo.url);      Request.Builder requestBuilder = new Request.Builder()          .get()          .url(newUrl);      if (offset > 0) {        requestBuilder.addheader("Range","bytes=" + offset + "-");      }      requestCall = okhttpClIEnt.newCall(requestBuilder.build());      response = requestCall.execute();      if (response.isRedirect()) {        newUrl = response.header("Location");        isRedirect = response.isRedirect();        redirectCount++;      }      if (redirectCount > MAX_REDIRECTS) {        throw new ProxyCacheException("Too many redirects: " + redirectCount);      }    } while (isRedirect);    return response;  }  public synchronized String getMime() throws ProxyCacheException {    if (TextUtils.isEmpty(sourceInfo.mime)) {      fetchContentInfo();    }    return sourceInfo.mime;  }  public String getUrl() {    return sourceInfo.url;  }  @OverrIDe  public String toString() {    return "OkhttpUrlSource{sourceInfo='" + sourceInfo + "}";  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android视频点播的实现代码(边播边缓存)全部内容,希望文章能够帮你解决Android视频点播的实现代码(边播边缓存)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1146252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存