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

import java.io.File;
import java.util.ArrayList;

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;

	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();
		}
		currentVideo = currentQuality = currentSegment = 0;
		this.videos = parsed;
		endReached = false;
	}
	
	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()
	{
		// Determina la seguent qualitat a partir de la velocitat
		if (currentSegment == segments.size())
		{
			if (endReached)
			{
				return null;
			}
			currentQuality = 0;
			currentSegment = 0;
			loadVideo();
		}
		Segment seg = segments.get(currentSegment++);
		Log.d(TAG, seg.getName() + " " + seg.getURL());
		return seg.getURL();
	}
	
	
	public void updateQuality(long bps)
	{
		if ((bps <= qualities.get(currentQuality).getQuality()) && (bps != -1))
		{
			int newQuality;
			for(newQuality = 0; newQuality < qualities.size(); newQuality++)
			{
				if(bps >= qualities.get(newQuality).getQuality())
				{
					break;
				}
			}
			if(currentQuality != newQuality)
			{
				currentQuality = newQuality;
				currentVideo--; //Corregimos el del loadVideo()
				loadVideo(); //Cargamos la nueva calidad
			}
		}
		else if((bps > qualities.get(currentQuality).getQuality()) && (bps != -1))
		{
			int newQuality;
			for(newQuality = qualities.size()-1; newQuality > 0; newQuality--)
			{
				if(bps <= qualities.get(newQuality).getQuality())
				{
					newQuality--;
					break;
				}
			}
			if(currentQuality != newQuality)
			{
				currentQuality = newQuality;
				currentVideo--; //Corregimos el del loadVideo()
				loadVideo(); //Cargamos la nueva calidad
			}
		}
	}
	
	
}