// Author: Sergi Diaz Planas
/*
    These functions manage webcam resources.
*/

localMediaStream = 0;   // media stream
frameCounter = 0;

// Start recording using available media
function startRecording(video) {
    // Try to access webcam
    navigator.getMedia = ( navigator.getUserMedia 
                        || navigator.webkitGetUserMedia 
                        || navigator.mozGetUserMedia );
	navigator.getMedia (
		// Restrictions
		{ video: true, audio: false },
		// Success callback
		function(stream) {
			localMediaStream = stream;		
            video.srcObject = localMediaStream;
            frameCounter = 0;
			video.play();
		},
		// Error callback (optional)
		function(err) {
			alert("Webcam could not be accessed!");
		}	
	);
}

// End recording
function stopRecording(video) {
	video.pause();
	video.src = "";
	localMediaStream.getTracks().forEach(function (track) { track.stop() }); // clear media stream
}

// Capture frame currently displayed on video
function captureFrame(video, scaleFactor) {
    
    if(scaleFactor == null){
        scaleFactor = 1;
    }
    var w = video.videoWidth * scaleFactor;
    var h = video.videoHeight * scaleFactor;
    var canvas = document.createElement('canvas');
    canvas.width  = w;
    canvas.height = h;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, w, h);
    return canvas;
}