web/static/res/js/incplayer.js
author Edwin Razafimahatratra <edwin@robotalismsoft.com>
Wed, 12 Dec 2012 04:01:13 +0100
changeset 47 dbd46ed42b0d
parent 46 542252e0c615
child 48 d92196482ad9
permissions -rw-r--r--
save

function IncPlayer()
{
	// --------------------------------------------------------------------------------------------------------------------
	// Members
	// --------------------------------------------------------------------------------------------------------------------

	// Global
	this.initDone = false;
	this.playerIsReady = false;
	this.iOS = false;

	// Sequences
	this.allSequencesData = [];
	this.sequences = [];

	// Popcorn objects
	this.videoDivId = "";
	this.videoExt = "";
	this.preferOgg = true; // debug
	this.popSeq = null;

	// Controls
	this.playButton = null;
	this.progressCurrent = null;
	this.progressDuration = null;
	this.hd = false;
	this.seekTime = 0.0;

	// Tools
	this.logiEnable = true;
	this.jsonData = [];

	// --------------------------------------------------------------------------------------------------------------------
	// Functions
	// --------------------------------------------------------------------------------------------------------------------

	this.init = function(videoDivId, playButtonId, progressCurrentId, progressDurationId, jsonFile, preferOgg)
	{
		this.videoDivId = videoDivId;
		this.preferOgg = preferOgg;

		// Control
		this.playButton = $("#" + playButtonId).get(0);
		this.progressCurrent = $("#" + progressCurrentId);
		this.progressDuration = $("#" + progressDurationId);

		// Video extention
		this.videoExt = this.getSupportedVideoExt();
		if (this.videoExt === "") {
			this.loge("your browser don't support HTML5 videos");
			return false;
		}

		// Detect iOS
		this.detectIOS();
		if (this.iOS) {
			this.logi("we are on iOS");
		}

		// Load all sequences data
		this.allSequencesData = this.loadJson(jsonFile);

		this.initDone = true;
		return true;
	};

	this.destroySequence = function()
	{
		if (this.popSeq !== null) {
			for (var i = 0; i < this.sequences.length; ++i) {			
				this.popSeq.eq(i).destroy();			
			}
			this.sequences = [];
			this.popSeq.remove();
		}		
	};

	this.createPopSequence = function(words)
	{
		if (!this.initDone) {
			this.loge("incplayer not initialized");
			return;
		}

		// Delete previous popcorn objects
		this.destroySequence();

		// Choose the 3 video
		this.choosePopSequence(words);

		// And cerate the popcorn sequence
		this.initPopSequence();
	};

	this.choosePopSequence = function(words)
	{
		this.sequences = [];
		var videos = this.allSequencesData.videos;
		this.sequences.push(this.getRandomVideos(words[0]));		
		this.sequences.push(this.getRandomVideos(words[1]));		
		this.sequences.push(this.getRandomVideos(words[2]));		

		// Set the video file name 
		var i;
		for (i = 0; i < this.sequences.length; ++i) {
			var file = this.sequences[i];
			
			// HD
			if(this.hd) {
				file += "hd"; 
			}

			// Extention
			file += "." + /*this.videoExt*/ "mp4"; // todo

			// Set the final file
			this.sequences[i] = file;
		}

		for (i = 0; i < this.sequences.length; ++i) {
			this.sequences[i] = { src: this.sequences[i], in: 0, out: -1 };
		}

		
		this.logi("choosed sequences:");
		for (i = 0; i < this.sequences.length; ++i) {
			this.logi(this.sequenceToString(i));
		}
	};

	this.getRandomVideos = function(word)
	{
		var index = this.getWordIndex(word);
		var videos = [];

		// Get all video affected by this word
		for (var i = 0; i < this.allSequencesData.videos.length; ++i) {
			var video = this.allSequencesData.videos[i];

			// We push has many time the url that the score for the word
			for (var j = 0; j < video.scoreWord[index]; ++j) {
				videos.push(video.src);
			}
		}

		return videos[this.random(0, videos.length)];
	}

	this.getWordIndex = function(word)
	{
		var words = this.allSequencesData.mots;
		for (var i = 0; i < words.length; ++i) {
			if (words[i] == word) {
				return i;
			}
		}
		console.log("getWordIndex erreur");
		return -1;
	};

	this.initPopSequence = function()
	{
		var self = this;

		// Create the popcorn sequencer
		self.popSeq = Popcorn.sequence(self.videoDivId, self.sequences);

		for (var i = 0; i < self.sequences.length; ++i) {
			
			var pop = self.popSeq.eq(i);

			// Hide controls
			pop.controls(false);

			self.listenEvent(pop, "playing", false, function() {
				self.displayPlayButton(false);
				self.logi("play sequence: " + self.sequenceToString(self.popSeq.active));
			});

			self.listenEvent(pop, "pause", false, function() {
				self.displayPlayButton(true);
				self.logi("pause sequence: " + self.sequenceToString(self.popSeq.active));
			});			

			self.listenEvent(pop, "timeupdate", false, function() {
				// Update the current time position
				$(self.progressCurrent).html(self.secondsToTime(self.popSeq.currentTime()));
			});

			self.listenEvent(pop, "canplaythrough", true, function() {
			});
		}

		self.popSeq.on("loadedmetadata", function() {

			self.playerIsReady = true;

			// todo
			// Set total duration
			//$(self.progressDuration).html(self.secondsToTime(self.popSeq.duration()));			

			if (!self.iOS) {
				// Automatic play
				self.ctrlPlay();
			}

			// Unlisten event
			self.popSeq.off("loadedmetadata");
			self.logi("the player is ready");
		});	

		self.popSeq.on("cycle", function() {
		});

		self.popSeq.on("ended", function() {
			// todo
			location.href = "transition.html";			
		});

	};

	this.listenEvent = function(pop, event, unlisten, func)
	{
		pop.on(event, function() {
			// Execute the function
			func();
	
			if (unlisten) {		
				// Unlisten event
				pop.off(event);
			}
		});
	};

	this.getCurrentPop = function()
	{
		var index = this.popSeq.active;
		if (index >= this.sequences.length) {
			index = this.sequences.length-1;
		}
		return this.popSeq.eq(index);
	};

	this.ctrlPlay = function()
	{
		if (!this.iOS && !this.playerIsReady) {
			// The video are not ready
			this.logi("can't play, the player is not ready");
			return;
		}

		if (this.getCurrentPop().paused()) {
			// Play
			this.popSeq.play();
		} else {
			// Pause
			this.popSeq.pause();
		}
	};

	this.ctrlNext = function()
	{
		if (!this.playerIsReady) {
			// The video are not ready
			this.logi("can't play, the player is not ready");
			return;
		}

		if (this.popSeq.active == this.sequences.length - 1) {
			// We are at the last video
			return;
		}

		// Go to the next video
		var jumpTime = this.popSeq.durationSeqs(this.popSeq.active + 1);
		this.popSeq.jumpTo(jumpTime);
	};

	this.ctrlPrev = function()
	{
		if (!this.playerIsReady) {
			// The video are not ready
			this.logi("can't play, the player is not ready");
			return;
		}

		var videoIndex = this.popSeq.active;
		if (videoIndex !== 0) {
			// If we are a less than 1 sec from the sequence start, we just to the prev sequence
			// else we jump to the start of the current sequence
			var jumpTimeStartCurrent = this.popSeq.durationSeqs(videoIndex);
			if (this.popSeq.currentTime() - jumpTimeStartCurrent < 1) {
				--videoIndex;
			}
		}

		// Go to the next video
		var jumpTime = this.popSeq.durationSeqs(videoIndex);
		this.popSeq.jumpTo(jumpTime);
	};

	this.ctrlFullScreen = function()
	{
		if (!this.playerIsReady) {
			// The video are not ready
			this.logi("can't play, the player is not ready");
			return;
		}

		this.logi("full screen");
	};
	
	this.ctrlHd = function()
	{
		if (!this.playerIsReady) {
			// The video are not ready
			this.logi("can't play, the player is not ready");
			return;
		}

		this.seekTime = this.popSeq.currentTime();
		this.hd = false;
		this.createPopSequence();

		this.logi("hd");
	};

	this.displayPlayButton = function(playIcon)
	{
		/*
		if (playIcon) {
			// Controller display
			this.playButton.src = 'static/res/img/ctrlplayover.jpg';
	    	this.playButton.onmouseover = function() {this.src='static/res/img/ctrlplayover.jpg';}; 
	    	this.playButton.onmouseout = function() {this.src='static/res/img/ctrlplay.jpg';};
		} else {
			// Controller display
			this.playButton.src = 'static/res/img/ctrlpauseover.jpg';
	    	this.playButton.onmouseover = function() {this.src='static/res/img/ctrlpauseover.jpg';}; 
	    	this.playButton.onmouseout = function() {this.src='static/res/img/ctrlpause.jpg';};
		}
		*/
	};
		 
	// --------------------------------------------------------------------------------------------------------------------
	// Tools Functions
	// --------------------------------------------------------------------------------------------------------------------

	this.logi = function(txt)
	{
		if (this.logiEnable) {
			console.log("info: " + txt);
		}
	};

	this.loge = function(txt)
	{
		console.log("error: " + txt);
	};

	this.loadJson = function(jsonFile)
	{
		var txt = this.loadTxtFile(jsonFile);
		return JSON.parse(txt);
	};

	this.loadTxtFile = function(jsonFile)
	{
		var xhr = new XMLHttpRequest();
		xhr.open("GET", jsonFile, false);  
		xhr.overrideMimeType('text/plain; charset=x-user-defined');

		try {
			xhr.send(null); 
		} catch(e) {
			return "";
		}

		if (xhr.status == 404) {
			return "";
		}
		
		var buffer;
		if (xhr.responseType == "arraybuffer") {
			buffer = xhr.response;
		} else if (xhr.mozResponseArrayBuffer === null) {
			buffer = xhr.mozResponseArrayBuffer;  
		} else {
			buffer = xhr.response;
		}
		return buffer;
	};

	this.random = function(min, max)
	{
		return Math.floor((Math.random()*(max-min))+min);
	};

	this.secondsToTime = function(sec)
	{
		var minutes = Math.floor(sec / 60);
		var seconds = Math.floor(sec - minutes * 60);
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
		return "" + minutes + "'" + seconds + "''";
	};

	this.sequenceToString = function(index)
	{
		return JSON.stringify(this.sequences[index]);
	};

	this.getSupportedVideoExt = function()
	{
		var v = document.createElement("video");

		if (v.canPlayType) {

		    // Check for Ogg support
		    if (this.preferOgg && v.canPlayType('video/ogg; codecs="theora"') !== "") {
		    	return "ogg";
		    }
		    
		    // Check for Webm support
		    if (v.canPlayType('video/webm; codecs="vp8, vorbis"') !== "") {
		    	return "webm";
		    }

		    // Check for MPEG-4 support
		    if (v.canPlayType('video/mp4; codecs="mp4v.20.8"' ) !== "") {
				return "mp4";
		    }

		    // Check for h264 support
		    if ((v.canPlayType('video/mp4; codecs="avc1.42E01E"' ) !== "" || v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'))) {
		    	return "mp4";
		    }
		}

		return "";
	};

	this.detectIOS = function()
	{
		var p = navigator.platform;
		if (p === 'iPad' || p === 'iPhone' || p === 'iPod') {
		    this.iOS = true;
		}		
	};
}

var incPlayer = new IncPlayer();