HLS.java 2.6 KB
package com.upc.pbe.upcnews;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import android.net.TrafficStats;
import android.util.Log;

//Gestor del protocol HTTP Live Streaming
public class HLS
{

	private static final String TAG = "HLS";
	private ArrayList<ParentList> videos;
	private ArrayList<Segment> segments;
	private ArrayList<Video> qualities;
	private int currentVideo;
	private int currentQuality; // 0 es la mas alta
	private int currentSegment;
	private boolean endReached;
	private String localFolder;
	private Descarrega d;
	private BandwidthMeasurer bm;

	public HLS(ArrayList<ParentList> parsed, String localFolder)
	{
		// Neteja el directori i inicialitza les variables
		File dir = new File(localFolder);
		String[] files = dir.list();
		for (int i = 0; i < files.length; i++)
		{
			File deleteme = new File(dir, files[i]);
			Log.d(TAG, "Esborrat " + files[i].toString());
			deleteme.delete();
		}
		currentQuality = 0;
		currentVideo = currentQuality = currentSegment = 0;
		this.videos = parsed;
		endReached = false;
		this.localFolder = localFolder;
		bm = new BandwidthMeasurer();
		d = new Descarrega();
	}

	public void loadVideo()
	{
		// Carrega la qualitat i, a partir d'aixo, el seguent segment
		qualities = videos.get(currentVideo++).getLists();
		segments = qualities.get(currentQuality).getSegments();
		if (currentVideo == videos.size())
		{
			endReached = true;
		}
	}

	public String next() throws IOException
	{
		// Determina la seguent qualitat a partir de la velocitat
		if (currentSegment == segments.size())
		{
			if (endReached)
			{
				return null;
			}
			loadVideo();
		}
		Segment seg = segments.get(currentSegment++);
		Log.d(TAG, seg.getName() + " " + seg.getURL());
		long startTime = System.currentTimeMillis();
		long segmentBytes = TrafficStats.getTotalRxBytes();
		d.descarregarguardar(seg.getURL(), localFolder);
		double bps = bm.Measure(segmentBytes, startTime);
		Log.d(TAG, "Velocitat actual (KB/s): " + (bps / 8e3));
		if ((bps < qualities.get(currentQuality).getQuality()) && (bps != -1))
		{
			currentQuality++;
		}
		return localFolder
				+ seg.getURL().substring(seg.getURL().lastIndexOf("/") + 1, seg.getURL().length());
	}

	public String previous() throws IOException
	{
		Segment seg = null;
		if (--currentSegment > 0)
		{
			--currentSegment;
		}
		seg = segments.get(currentSegment++);
		return localFolder + seg.getURL().substring(seg.getURL().lastIndexOf("/") + 1, seg.getURL().length());
	}

	public void setDefQuality(int q)
	{
		currentQuality = q;
	}
}