How to render videos in PixiJS without lowering performance - javascript

I am building a game with PixiJS and need to use videos as the background. I am able to load the video and have it fill the canvas but when the video plays I get a major performance hit on the rest of the game.
I have seen something about rendering the video with its own ticker so it's not rendering at ~60fps but I have not been able to figure out how to add multiple ticker instances in PixiJS.
Here is my code for the video:
let video = document.createElement('video');
video.preload = 'auto';
video.loop = true;
video.autoplay = false;
video.src = '../assets/placeholder/VIDEO FILE.mp4';
let texture = PIXI.Texture.from(video);
let videoSprite = new PIXI.Sprite(texture);
app.stage.addChild(videoSprite);
And here is my render code:
function render() {
app.ticker.add((delta) => {
elapsed += delta;
gameLoop()
});
}
Is this the proper way to use video textures in PixiJS?

I was able to fix this issue using VideoResource and setting the FPS:
const videoResource = new PIXI.resources.VideoResource(video);
videoResource.updateFPS = 30 // set video to render at 30FPS to avoid performance issues
let texture = PIXI.Texture.from(videoResource);
let videoSprite = new PIXI.Sprite(texture);
this.backgroundVideo = videoSprite
this.backgroundVideo.height = h
this.backgroundVideo.width = w
app.stage.addChild(this.backgroundVideo);

Related

How to dynamically create and play audio with "AudioContext" in a web browser (using PyScript)?

Using the javascript AudioContext interface I want to create an Audiostream that is playing a dynamically created 1-second long waveform continuously. That waveform is supposed to be updated when I change a slider on the html page etc.
So basically I want to feed in a vector containing 44100 floats that represents that 1-second long waveform.
So far I have
const audio = new AudioContext({
latencyHint: "interactive",
sampleRate: 44100,
});
but I am not sure how to apply that vector/list/data structure with my actual waveform.
Hint: I want to add audio to this PyScript example.
This example might help you, it generates a random float array and plays that. I think. You can click "go" multiple times to generate a new wave.
WARNING: BE CAREFUL WITH THE VOLUME IF YOU RUN THIS. IT CAN BE DANGEROUSLY LOUD!
function makeWave(audioContext) {
const floats = []
for (let i = 44000;i--;) floats.push(Math.random()*2 - 1)
console.log("New waveform done")
const sineTerms = new Float32Array(floats)
const cosineTerms = new Float32Array(sineTerms.length)
const customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms)
return customWaveform
}
let audioCtx, oscillator, gain, started = false
document.querySelector("#on").addEventListener("click", () => {
// Initialize only once
if (!gain) {
audioCtx = new AudioContext() // Controls speakers
gain = audioCtx.createGain() // Controls volume
oscillator = audioCtx.createOscillator() // Controls frequency
gain.connect(audioCtx.destination) // connect gain node to speakers
oscillator.connect(gain) // connect oscillator to gain
oscillator.start()
}
const customWaveform = makeWave(audioCtx)
oscillator.setPeriodicWave(customWaveform)
gain.gain.value = 0.02 // ☠🕱☠ CAREFUL WITH VOLUME ☠🕱☠
})
document.querySelector("#off").addEventListener("click", () => {
gain.gain.value = 0
})
<b>SET VOLUME VERY LOW BEFORE TEST</b>
<button id="on">GO</button>
<button id="off">STOP</button>

Save ALL video frames to folder in Javascript [duplicate]

I'm working on a client-side project which lets a user supply a video file and apply basic manipulations to it. I'm trying to extract the frames from the video reliably. At the moment I have a <video> which I'm loading selected video into, and then pulling out each frame as follows:
Seek to the beginning
Pause the video
Draw <video> to a <canvas>
Capture the frame from the canvas with .toDataUrl()
Seek forward by 1 / 30 seconds (1 frame).
Rinse and repeat
This is a rather inefficient process, and more specifically, is proving unreliable as I'm often getting stuck frames. This seems to be from it not updating the actual <video> element before it draws to the canvas.
I'd rather not have to upload the original video to the server just to split the frames, and then download them back to the client.
Any suggestions for a better way to do this are greatly appreciated. The only caveat is that I need it to work with any format the browser supports (decoding in JS isn't a great option).
[2021 update]: Since this question (and answer) has first been posted, things have evolved in this area, and it is finally time to make an update; the method that was exposed here went out-of-date, but luckily a few new or incoming APIs can help us better in extracting video frames:
The most promising and powerful one, but still under development, with a lot of restrictions: WebCodecs
This new API unleashes access to the media decoders and encoders, enabling us to access raw data from video frames (YUV planes), which may be a lot more useful for many applications than rendered frames; and for the ones who need rendered frames, the VideoFrame interface that this API exposes can be drawn directly to a <canvas> element or converted to an ImageBitmap, avoiding the slow route of the MediaElement.
However there is a catch, apart from its current low support, this API needs that the input has been demuxed already.
There are some demuxers online, for instance for MP4 videos GPAC's mp4box.js will help a lot.
A full example can be found on the proposal's repo.
The key part consists of
const decoder = new VideoDecoder({
output: onFrame, // the callback to handle all the VideoFrame objects
error: e => console.error(e),
});
decoder.configure(config); // depends on the input file, your demuxer should provide it
demuxer.start((chunk) => { // depends on the demuxer, but you need it to return chunks of video data
decoder.decode(chunk); // will trigger our onFrame callback
})
Note that we can even grab the frames of a MediaStream, thanks to MediaCapture Transform's MediaStreamTrackProcessor.
This means that we should be able to combine HTMLMediaElement.captureStream() and this API in order to get our VideoFrames, without the need for a demuxer. However this is true only for a few codecs, and it means that we will extract frames at reading speed...
Anyway, here is an example working on latest Chromium based browsers, with chrome://flags/#enable-experimental-web-platform-features switched on:
const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (window.MediaStreamTrackProcessor) {
let stopped = false;
const track = await getVideoTrack();
const processor = new MediaStreamTrackProcessor(track);
const reader = processor.readable.getReader();
readChunk();
function readChunk() {
reader.read().then(async({ done, value }) => {
if (value) {
const bitmap = await createImageBitmap(value);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
value.close();
}
if (!done && !stopped) {
readChunk();
} else {
select.disabled = false;
}
});
}
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoTrack() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
const [track] = video.captureStream().getVideoTracks();
video.onended = (evt) => track.stop();
return track;
}
video,canvas {
max-width: 100%
}
<button>start</button>
<select disabled>
</select>
<canvas></canvas>
The easiest to use, but still with relatively poor browser support, and subject to the browser dropping frames: HTMLVideoElement.requestVideoFrameCallback
This method allows us to schedule a callback to whenever a new frame will be painted on the HTMLVideoElement.
It is higher level than WebCodecs, and thus may have more latency, and moreover, with it we can only extract frames at reading speed.
const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (HTMLVideoElement.prototype.requestVideoFrameCallback) {
let stopped = false;
const video = await getVideoElement();
const drawingLoop = async(timestamp, frame) => {
const bitmap = await createImageBitmap(video);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
if (!video.ended && !stopped) {
video.requestVideoFrameCallback(drawingLoop);
} else {
select.disabled = false;
}
};
// the last call to rVFC may happen before .ended is set but never resolve
video.onended = (evt) => select.disabled = false;
video.requestVideoFrameCallback(drawingLoop);
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoElement() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
return video;
}
video,canvas {
max-width: 100%
}
<button>start</button>
<select disabled>
</select>
<canvas></canvas>
For your Firefox users, Mozilla's non-standard HTMLMediaElement.seekToNextFrame()
As its name implies, this will make your <video> element seek to the next frame.
Combining this with the seeked event, we can build a loop that will grab every frame of our source, faster than reading speed (yeah!).
But this method is proprietary, available only in Gecko based browsers, not on any standard tracks, and probably gonna be removed in the future when they'll implement the methods exposed above.
But for the time being, it is the best option for Firefox users:
const frames = [];
const button = document.querySelector("button");
const select = document.querySelector("select");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
button.onclick = async(evt) => {
if (HTMLMediaElement.prototype.seekToNextFrame) {
let stopped = false;
const video = await getVideoElement();
const requestNextFrame = (callback) => {
video.addEventListener("seeked", () => callback(video.currentTime), {
once: true
});
video.seekToNextFrame();
};
const drawingLoop = async(timestamp, frame) => {
if(video.ended) {
select.disabled = false;
return; // FF apparently doesn't like to create ImageBitmaps
// from ended videos...
}
const bitmap = await createImageBitmap(video);
const index = frames.length;
frames.push(bitmap);
select.append(new Option("Frame #" + (index + 1), index));
if (!video.ended && !stopped) {
requestNextFrame(drawingLoop);
} else {
select.disabled = false;
}
};
requestNextFrame(drawingLoop);
button.onclick = (evt) => stopped = true;
button.textContent = "stop";
} else {
console.error("your browser doesn't support this API yet");
}
};
select.onchange = (evt) => {
const frame = frames[select.value];
canvas.width = frame.width;
canvas.height = frame.height;
ctx.drawImage(frame, 0, 0);
};
async function getVideoElement() {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm";
document.body.append(video);
await video.play();
return video;
}
video,canvas {
max-width: 100%
}
<button>start</button>
<select disabled>
</select>
<canvas></canvas>
The least reliable, that did stop working over time: HTMLVideoElement.ontimeupdate
The strategy pause - draw - play - wait for timeupdate used to be (in 2015) a quite reliable way to know when a new frame got painted to the element, but since then, browsers have put serious limitations on this event which was firing at great rate and now there isn't much information we can grab from it...
I am not sure I can still advocate for its use, I didn't check how Safari (which is currently the only one without a solution) handles this event (their handling of medias is very weird for me), and there is a good chance that a simple setTimeout(fn, 1000 / 30) loop is actually more reliable in most of the cases.
Here's a working function that was tweaked from this question:
async function extractFramesFromVideo(videoUrl, fps = 25) {
return new Promise(async (resolve) => {
// fully download it first (no buffering):
let videoBlob = await fetch(videoUrl).then((r) => r.blob());
let videoObjectUrl = URL.createObjectURL(videoBlob);
let video = document.createElement("video");
let seekResolve;
video.addEventListener("seeked", async function () {
if (seekResolve) seekResolve();
});
video.src = videoObjectUrl;
// workaround chromium metadata bug (https://stackoverflow.com/q/38062864/993683)
while (
(video.duration === Infinity || isNaN(video.duration)) &&
video.readyState < 2
) {
await new Promise((r) => setTimeout(r, 1000));
video.currentTime = 10000000 * Math.random();
}
let duration = video.duration;
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
let [w, h] = [video.videoWidth, video.videoHeight];
canvas.width = w;
canvas.height = h;
let frames = [];
let interval = 1 / fps;
let currentTime = 0;
while (currentTime < duration) {
video.currentTime = currentTime;
await new Promise((r) => (seekResolve = r));
context.drawImage(video, 0, 0, w, h);
let base64ImageData = canvas.toDataURL();
frames.push(base64ImageData);
currentTime += interval;
}
resolve(frames);
});
}
Usage:
let frames = await extractFramesFromVideo("https://example.com/video.webm");
Note that there's currently no easy way to determine the actual/natural frame rate of a video unless perhaps you use ffmpeg.js, but that's a 10+ megabyte javascript file (since it's an emscripten port of the actual ffmpeg library, which is obviously huge).
2023 answer:
If you want to extract all frames reliably (i.e. no "seeking" and missing frames), and do so as fast as possible (i.e. not limited by playback speed or other factors) then you probably want to use the WebCodecs API. As of writing it's supported in Chrome and Edge. Other browsers will soon follow - hopefully by the end of 2023 there will be wide support.
I put together a simple library for this, but it currently only supports mp4 files. Here's an example:
<canvas id="canvasEl"></canvas>
<script type="module">
import getVideoFrames from "https://deno.land/x/get_video_frames#v0.0.8/mod.js"
let ctx = canvasEl.getContext("2d");
// `getVideoFrames` requires a video URL as input.
// If you have a file/blob instead of a videoUrl, turn it into a URL like this:
let videoUrl = URL.createObjectURL(fileOrBlob);
await getVideoFrames({
videoUrl,
onFrame(frame) { // `frame` is a VideoFrame object: https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame
ctx.drawImage(frame, 0, 0, canvasEl.width, canvasEl.height);
frame.close();
},
onConfig(config) {
canvasEl.width = config.codedWidth;
canvasEl.height = config.codedHeight;
},
});
URL.revokeObjectURL(fileOrBlob); // revoke URL to prevent memory leak
</script>
Demo: https://jsbin.com/mugoguxiha/edit?html,output
Github: https://github.com/josephrocca/getVideoFrames.js
(Note that the WebCodecs API is mentioned in #Kaiido's excellent answer, but this API alone unfortunately doesn't solve the issue - the example above uses mp4box.js to handle the stuff that the WebCodecs doesn't handle. Perhaps WebCodecs will eventually support the container side of things and this answer will become mostly irrelevant, but until then I hope that this is useful.)

How to screen record a rolling n-second window

I'm aware of the MediaRecorder API and how to record screen/audio/video, and then download those recordings. I'm also aware of npm modules such as react-media-recorder that leverage that API.
I would like to record a rolling n-second window of screen recording, to allow the user to create clips and then be able to share those clips. I cannot record the entire session as I don't know how long they will last, meaning I don't know how big the recordings might get (I assume there is a limit to what the recording can have in memory.)
Is there any easy way to use MediaRecorder to record a rolling window (i.e. to always have in memory the last 30 seconds recorded)?
I spent quite a while trying to make this work. Unfortunately, the only solution that works for me involves making 30 recorders.
The naive solution to this problem is to call recorder.start(1000) to record data in one second intervals, then maintain a circular buffer on the dataavailable event. The issue with this is that MediaRecorder supports a very, very limited number of encodings. None of these encodings allow data packets to be dropped from the beginning, since they contain important metadata. With better understanding of the protocols, I'm sure that it is to some extent possible to make this strategy work. However, simply concatenating the packets together (when some are missing) does not create a valid file.
Another attempt I made used two MediaRecorder objects at once. One of them would record second-long start packets, and the other would record regular data packets. When taking a clip, this then combined a start packet from the first recorder with the packets from the second. However, this usually resulted in corrupted recordings.
This solution is not fantastic, but it does work: the idea is to keep 30 MediaRecorder objects, each offset by one second. For the sake of this demo, the clips are 5 seconds long, not 30:
<canvas></canvas><button>Clip!</button>
<style>
canvas, video, button {
display: block;
}
</style>
<!-- draw to the canvas to create a stream for testing -->
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// fill background with white
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// randomly draw stuff
setInterval(() => {
const x = Math.floor(Math.random() * canvas.width);
const y = Math.floor(Math.random() * canvas.height);
const radius = Math.floor(Math.random() * 30);
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.stroke();
}, 100);
</script>
<!-- actual recording -->
<script>
// five second clips
const LENGTH = 5;
const codec = 'video/webm;codecs=vp8,opus'
const stream = canvas.captureStream();
// circular buffer of recorders
let head = 0;
const recorders = new Array(LENGTH)
.fill()
.map(() => new MediaRecorder(stream, { mimeType: codec }));
// start them all
recorders.forEach((recorder) => recorder.start());
let data = undefined;
recorders.forEach((r) => r.addEventListener('dataavailable', (e) => {
data = e.data;
}));
setInterval(() => {
recorders[head].stop();
recorders[head].start();
head = (head + 1) % LENGTH;
}, 1000);
// download the data
const download = () => {
if (data === undefined) return;
const url = URL.createObjectURL(data);
// download the url
const a = document.createElement('a');
a.download = 'test.webm';
a.href = url;
a.click();
URL.revokeObjectURL(url);
};
// stackoverflow doesn't allow downloads
// we show the clip instead
const show = () => {
if (data === undefined) return;
const url = URL.createObjectURL(data);
// display url in new video element
const v = document.createElement('video');
v.src = url;
v.controls = true;
document.body.appendChild(v);
};
document.querySelector('button').addEventListener('click', show);
</script>

Recording fabricjs as video with a video element from external link inside of the canvas

I am trying to record a fabricjs canvas as a video that has a video element inside o it,
when i record the canvas without the video element it records the canvas and the other elements, but when i add the video it doesn't seem to record anything, it does not record anything.
this.videoElement = new fabric.Image(this.getVideoElement(this.action.link), {
left: 0,
top: 0,
crossOrigin: 'anonymous',
id: 'videoRecordElement',
});
this.canvas.add(this.videoElement);
let self = this;
fabric.util.requestAnimFrame(function render() {
self.canvas.renderAll();
fabric.util.requestAnimFrame(render);
});
this.videoElement.getElement().play();
const chunks = []; // here we will store our recorded media chunks (Blobs)
const stream = (this.drawingCanvas.nativeElement as any).captureStream(); // grab our canvas MediaStream
this.rec = new MediaRecorder(stream, {mimeType: 'video/webm;codecs=vp8'}); // init the recorder
// every time the recorder has new data, we will store it in our array
this.rec.ondataavailable = e => chunks.push(e.data);
// only when the recorder stops, we construct a complete Blob from all the chunks
this.rec.onstop = e => this.exportVid(new Blob(chunks, {type: 'video/mp4'}));
this.rec.start();
getVideoElement(url) {
var videoE = document.createElement('video');
videoE.width = document.getElementById('videoConatiner').clientWidth;
videoE.height = document.getElementById('videoConatiner').clientHeight;
videoE.muted = true;
videoE.controls = true;
(videoE as any).crossorigin = "anonymous";
videoE.autoplay = true;
var source = document.createElement('source');
source.src = url;
source.type = 'video/mp4';
videoE.appendChild(source);
return videoE;
}
I am using fabricjs inside an angular project
if the video being played is from a different domain (or more specifically, a different origin), it cannot be captured with MediaRecorder due to the same-origin policy

OpenCV.js side-effect: video is being pushed into new empty matrix without being requested

I am trying to debug a problem I'm having with OpenCV.js. I am trying to create a simple circle-finding function, but my video feed is being displayed in my canvas. I've boiled it down to the smallest set that shows the issue.
What makes no sense is that I create a new, empty matrix and display it, and I see my video feed in it.
I start with the typical way of detecting circles: Stream the video into matrix scrMat, convert srcMat into a grayscale grayMat, and then call HoughCircles to detect circles from grayMat into circlesMat.
Then, independently, I create a new displayMat and display it.
I see the output below, where the right-handside is displayMat.
Somehow displayMat is being filled. The effect goes away if I comment out the HoughCircles line.
How is this happening?
const cv = require('opencv.js'); // v1.2.1
const video = document.getElementById('video');
const width = 300;
const height = 225;
const FPS = 30;
let stream;
let srcMat = new cv.Mat(height, width, cv.CV_8UC4);
let grayMat = new cv.Mat(height, width, cv.CV_8UC1);
let circlesMat = new cv.Mat();
const cap = new cv.VideoCapture(video);
export default function capture() {
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(_stream => {
stream = _stream;
video.srcObject = stream;
video.play();
setTimeout(processVideo, 0)
})
.catch(err => console.log(`An error occurred: ${err}`));
function processVideo () {
const begin = Date.now();
// these next three lines shouldn't affect displayMat
cap.read(srcMat);
cv.cvtColor(srcMat, grayMat, cv.COLOR_RGBA2GRAY);
// if this line is commented out, the effect goes away
cv.HoughCircles(grayMat, circlesMat, cv.HOUGH_GRADIENT, 1, 45, 75, 40, 0, 0);
// this ought to simply create a new matrix and draw it
let displayMat = new cv.Mat(height, width, cv.CV_8UC1);
cv.imshow('canvasOutput', displayMat);
const delay = 1000/FPS - (Date.now() - begin);
setTimeout(processVideo, delay);
}
}
Most probably displayMat is created in memory place where some image processing was done with HoughCircles() or something. That memory was released and became available for allocating new objects in it, but neither its freeing nor new Mat creation did not clear that memory block.
So just clean the displayMat first, as it is constructed on place of some "garbage" that left from previous operations, or use cv.Mat.zeros() to construct displayMat (zeros() fills the whole new matrix buffer with zeros).
let displayMat = cv.Mat.zeros(height, width, cv.CV_8UC1);

Categories