Analysis of Androidvideocache Source code

Source: Internet
Author: User

1. Side Play side cache

Video playback while playing side cache, so that users can save traffic when playing again, improve the user experience, which is a very common need for video playback. However, Android Videoview does not provide such a feature.

There's an open source library, GitHub. Address: Https://github.com/danikula/AndroidVideoCache

2. Briefly describe the general principle of implementation of Androidvideocache

As we all know, Videoview.setvideopath (Proxyurl), is also the HTTP request, and the HTTP underlying is the TCP protocol socket implementation. Androidvideocache implementation is in the TCP layer of a Socketserver proxy server, that is Videoview.setvideopath (Proxyurl); The request is to request to the proxy server socketserver first, then the proxy server Socketserver again to request the real server. This way, the proxy server socketserver can request the real server to download the video (Androidvideocache is a multipart download, that is, the breakpoint continues to pass, each time 8 * 1024 size), and then the video response to the request. Of course, the proxy server socketserver will also first determine whether the video has been downloaded cache, if you have downloaded the cache after the direct use of local cache video.

3. Androidvideocache Source Code Brief

1) app Global set up a local socket proxy server

InetAddress inetaddress = Inetaddress.getbyname (proxy_host);
This.serversocket = new ServerSocket (0, 8, inetaddress);

2) Getproxyurl method, first determine whether it has been cached, if you are directly using the local cache. If no, determine if the proxy server Socketserver is available

public string Getproxyurl (string url, Boolean Allowcachedfileuri) {
if (Allowcachedfileuri && iscached (URL)) {//cache OK
File cachefile = getcachefile (URL);
Touchfilesafely (Cachefile); Touch the file, make the file time up to date, for LRUCache cache, LRUCache cache is sorted by time.
Return Uri.fromfile (Cachefile). toString ();
}
Return isAlive ()?  Appendtoproxyurl (URL): URL; The IsAlive () method is to ping the proxy server socketserver to see if it is available? Yes, package into Proxyurl, no, use source URL, do not cache
}

3) Processsocket handles all requests coming in the socket, including the ping and Videoview.setvideopath (Proxyurl) sockets

private void Processsocket (socket socket) {
Getrequest request = Getrequest.read (Socket.getinputstream ());
Log.debug ("Request to Cache Proxy:" + request);
String url = proxycacheutils.decode (Request.uri);
if (pinger.ispingrequest (URL)) {//If it is ping, return ping response
Pinger.responsetoping (socket);
} else {//video socket, start the corresponding client to process
Httpproxycacheserverclients clients = getclients (URL);
Clients.processrequest (request, socket);
}
}

4) Clients.processrequest (request, socket), method implementation

public void ProcessRequest (Getrequest request, socket socket) throws Proxycacheexception, IOException {
Startprocessrequest (); This method is actually to get a proxycache correspondence
try {
Clientscount.incrementandget ();
Proxycache.processrequest (request, socket); Handing it over to Proxycache.
} finally {
Finishprocessrequest ();
}
}

Private synchronized void Startprocessrequest () throws Proxycacheexception {
Proxycache = Proxycache = = null?  Newhttpproxycache (): Proxycache; Newhttpproxycache () This method prepares URLs, caches file paths, listeners, etc...
}

5) Proxycache.processrequest (request, socket), method implementation

public void ProcessRequest (Getrequest request, socket socket) throws IOException, Proxycacheexception {
OutputStream out = new Bufferedoutputstream (Socket.getoutputstream ()); Create a response stream for a socket
String responseheaders = newresponseheaders (request);
Out.write (Responseheaders.getbytes ("UTF-8"));

Long offset = Request.rangeoffset;
if (Isusecache (Request)) {//Determine if the cache is used? Is
Responsewithcache (out, offset); Caching and responding
} else {//Do not use cache
Responsewithoutcache (out, offset); Do not cache and respond
}
}

6) Responsewithcache (out, offset), method implementation

while (!cache.iscompleted () && cache.available () < (offset + length) &&!stopped) {
Readsourceasync (); Asynchronously requests a real server to read the data, and then notifies it when it reads
Waitforsourcedata (); Lock pending notification of Readsourceasync ()
Checkreadsourceerrorscount (); Checksum error
}

6-1) Readsourceasync (); method last callback with Readsource () method

private void Readsource () {
Long sourceavailable =-1;
Long offset = 0;
try {
offset = cache.available ();
Source.open (offset);
sourceavailable = Source.length ();
byte[] buffer = new Byte[proxycacheutils.default_buffer_size]; Every time I read so much data proxycacheutils.default_buffer_size
int readbytes;
while ((readbytes = source.read (buffer))! =-1) {
Synchronized (Stoplock) {
if (isStopped ()) {
Return
}
Cache.append (buffer, readbytes); Append to Cache
}
Offset + = readbytes;
Notifynewcachedataavailable (offset, sourceavailable); Notifications have data available, that is, wake-up Waitforsourcedata () method, let while (!cache.iscompleted () && cache.available () < (offset + length) &&!stopped) continue to judge execution
}
Trycomplete (); This method determines whether the file has already been downloaded and completed. The cache file is a temporary. Download is a suffix file, the fragment cache completes the entire video file, and the modified file name is the filename associated with the request URL
Onsourceread ();
} catch (Throwable e) {
Readsourceerrorscount.incrementandget ();
OnError (e);
} finally {
Closesource ();
Notifynewcachedataavailable (offset, sourceavailable);
}
}

7) Responsewithoutcache (out, offset), method implementation

private void Responsewithoutcache (OutputStream out, long offset) throws Proxycacheexception, IOException {
Httpurlsource Newsourcenocache = new Httpurlsource (This.source);
try {
Newsourcenocache.open ((int) offset); This method inside opens HttpURLConnection
byte[] buffer = new Byte[default_buffer_size];
int readbytes;
while ((readbytes = newsourcenocache.read (buffer))! =-1) {//read reads HttpURLConnection's getInputStream () data
Out.write (buffer, 0, readbytes);
Offset + = readbytes;
}
Out.flush ();
} finally {
Newsourcenocache.close ();
}
}

  

Analysis of Androidvideocache Source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.