欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-17 08:53:10
简述 一些知名的视频app客户端(优酷,爱奇艺)播放视频的时候都有一些缓存进度(二级进度缓存),还有一些短视频app,都有边播边缓的处理。还有就是当文件缓存完毕了再次播放...

简述

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

开源的项目

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

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

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

优化点比如:

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

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

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

  1. 采用了本地代理服务的方式,通过原始url给播放器返回一个本地代理的一个url ,代理url类似:http://127.0.0.1:57430/xxxx;然后播放器播放的时候请求到了你本地的代理上了。
  2. 本地代理采用serversocket监听127.0.0.1的有效端口,这个时候手机就是一个服务器了,客户端就是socket,也就是播放器。
  3. 读取客户端就是socket来读取数据(http协议请求)解析http协议。
  4. 根据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, length, mime);
      this.sourceinfostorage.put(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.printstacktrace();
        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, 0, 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, length, mime);
      this.sourceinfostorage.put(sourceinfo.url, sourceinfo);
      videocachelog.info(tag, "content info for `" + sourceinfo.url + "`: mime: " + mime + ", content-length: " + length);
    } catch (ioexception e) {
      videocachelog.error(tag, "error fetching info from " + sourceinfo.url, 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, 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 {
      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 + "}";
  }
}

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