<html>
<head>
<title>Using Screen Capture API - RJM Programming - June, 2022 ... thanks to https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture and https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API</title>
<style>
body {
padding: 0;
margin: 0;
background: linear-gradient(rgba(255,255,255,0.9),rgba(255,255,255,0.9)),url('./screen_capture_api_test.gif') right;
background-size: contain;
background-repeat: no-repeat;
}

svg:not(:root) {
display: block;
}

.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}

.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}

.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}

td { vertical-align: top; }

#video {
border: 1px solid #999;
width: 98%;
max-width: 860px;
}

.error {
color: red;
}

.warn {
color: orange;
}

.info {
color: darkgreen;
}

button {
vertical-align: top;
}
</style>
<script type='text/javascript'>


// Options for getDisplayMedia()

var displayMediaOptions = {
video: {
cursor: "always"
},
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 44100
}
};

const gdmOptions = {
video: {
cursor: "always"
},
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 44100
}
};

var recordedChunks = [];
var mediaRecorder=null;
var blob=null, bloba=null;
var url=null, audioUrl=null;
var a=null;

async function startCapture() {
recordedChunks = [];

if (typeof(logElem) !== 'undefined') {
console.log(typeof(logElem));
console.log(typeof(stream));
logElem.innerHTML = "";
}

try {
if (typeof(videoElem) !== 'undefined') {
videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
dumpOptionsInfo();
}
} catch(err) {
console.error("Error: " + err);
}

if (typeof(stream) === 'undefined') {
//console.log('precanvas');
const canvas = document.querySelector("canvas");
//console.log('canvas=' + canvas);

// Optional frames per second argument.
const stream = canvas.captureStream(25);
//const recordedChunks = [];

//console.log(stream);
window.stream = stream;
const options = { mimeType: "video/webm;codecs=vp9" }; // vs 9
//mediaRecorder = new MediaRecorder(window.stream, options);
mediaRecorder = new MediaRecorder(videoElem.srcObject, options);

//const _this = this;

mediaRecorder.ondataavailable = function(e) {
//console.log("data_available " + e.data.size);
if (e.data.size > 0){
recordedChunks.push(e.data);
// _this.setState({recordedChunks:recordedChunks});
//download();
}
};

mediaRecorder.start(1000);

//mediaRecorder.onstop = (event) => {
//};

mediaRecorder.onstop = function(e) {
if (recordedChunks) {
if(1 == 5 && recordedChunks.length > 0 && document.getElementById('audio')) {
//const audio = document.querySelector('audio');
audio.controls = true;
bloba = new Blob(recordedChunks, { 'type' : 'audio/ogg; codecs=opus' });
audioURL = window.URL.createObjectURL(bloba);
audio.src = audioURL;
}
}
};

//setTimeout(event => {
// console.log("recording1 vs " + mediaRecorder.state);
// mediaRecorder.stop();
// console.log("recording2 vs " + mediaRecorder.state);
// mediaRecorder.requestData();
// console.log("recording3 vs " + mediaRecorder.state);
// mediaRecorder.start(1000);
// console.log("recording4 vs " + mediaRecorder.state);
//}, 9000);

//this.setState({mediaRecorder:mediaRecorder});

//mediaRecorder.ondataavailable = handleDataAvailable;
//mediaRecorder.start();

// demo: to download after 9sec
//setTimeout(event => {
// console.log("stopping");
// mediaRecorder.stop();
//}, 9000);
//} else if (window.stream) {
}

if (document.getElementById('mybody')) {
document.getElementById('mybody').style.backgroundImage='none';
}
}

function stopCapture(evt) {
let tracks = videoElem.srcObject.getTracks();

//tracks.forEach(track => mediaRecorder.addTrack(track, stream));
tracks.forEach(track => track.stop());
videoElem.srcObject = null;
document.getElementById('mybody').style.background="linear-gradient(rgba(255,255,255,0.9),rgba(255,255,255,0.9)),url('./screen_capture_api_test.gif') right";
document.getElementById('mybody').style.backgroundSize="contain";
document.getElementById('mybody').style.backgroundRepeat='no-repeat';
if (mediaRecorder) {
mediaRecorder.stop();
}
}

function dumpOptionsInfo() {
const videoTrack = videoElem.srcObject.getVideoTracks()[0];

console.info("Track settings:");
console.info(JSON.stringify(videoTrack.getSettings(), null, 2));
console.info("Track constraints:");
console.info(JSON.stringify(videoTrack.getConstraints(), null, 2));
download();
}

function handleDataAvailable(event) {
//console.log("data-available " + event.data.size);
if (event.data.size > 0) {
recordedChunks.push(event.data);
//console.log(recordedChunks);
//download();
} else {
// ...
}
}

function download() {
//console.log("downloading 0");
// let dtracks = videoElem.srcObject.getTracks();
//tracks.forEach(track => mediaRecorder.addTrack(track, stream));
// dtracks.forEach(track => window.stream.addTrack(track));
//console.log("recording1 vs " + mediaRecorder.state);
//mediaRecorder.stop();
//console.log("recording2 vs " + mediaRecorder.state);
if (mediaRecorder) {
if (('' + mediaRecorder.state) != 'inactive') {
mediaRecorder.requestData();
}
//console.log("recording3 vs " + mediaRecorder.state);
blob = new Blob(recordedChunks, {
type: "video/webm"
});
url = URL.createObjectURL(blob);
a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = "screen_capture_api_test.webm";
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
//window.URL.revokeObjectURL(url);
//console.log("downloading 1");
//mediaRecorder.start(1000);
//console.log("recording4 vs " + mediaRecorder.state);
}
}

</script>
</head>
<body id=mybody data-onload=onl();>
<table id=mytable><tr><td><button id=start>Capture<br>Screen<br>Start ▶</button> <button onclick="download();" id=download>Download 📹</button> <button id=stop>Stop ⏹</button><br><br>
<video id=video autoplay></video><audio id=audio autoplay></audio>
<br>

<!--strong id=stronge>Log:</strong>
<br>
<pre id="log"></pre--></td><td style="width:20%;"><h2>Using Screen Capture API</h2><h3>RJM Programming - June, 2022</h3><h4>Thanks to <a target=_blank href='//developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture' title='https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture'>https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture</a> and <a target=_blank title='https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API' href='//developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API'>https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API  </a></h4><br><br><strong id=stronge>Log:</strong>
<br>
<pre id="log"></pre><canvas id=canvas></canvas></td></tr></table>

<script type='text/javascript'>
const videoElem = document.getElementById("video");
const audioElem = document.getElementById("audio");
const logElem = document.getElementById("log");
const startElem = document.getElementById("start");
const stopElem = document.getElementById("stop");

console.log = msg => logElem.innerHTML += `${msg}<br>`;
console.error = msg => logElem.innerHTML += `<span class="error">${msg}</span><br>`;
console.warn = msg => logElem.innerHTML += `<span class="warn">${msg}<span><br>`;
console.info = msg => logElem.innerHTML += `<span class="info">${msg}</span><br>`;

// Set event listeners for the start and stop buttons ... thanks to https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture
startElem.addEventListener("click", function(evt) {
startCapture();
}, false);

stopElem.addEventListener("click", function(evt) {
stopCapture();
}, false);

if (document.URL.indexOf('iframe=') == -1) {
document.getElementById('video').style.display='none';
document.getElementById('audio').style.display='none';
document.getElementById('log').style.display='none';
document.getElementById('start').style.display='none';
document.getElementById('stop').style.display='none';
document.getElementById('stronge').style.display='none';
document.getElementById('mytable').style.display='none';
document.body.style.backgroundImage='none';
document.write('<iframe class="sample-code-frame" title="Simple screen capture sample" id="frame_simple_screen_capture" min-width="640" min-height="680" width="100%" height="100%" src="./screen_capture_api_test.htm?iframe=yes' + Math.floor(Math.random() * 19875643) + '" allow="display-capture" loading="lazy"></iframe>');
}
</script>
</body>
</html>