forked from collidingScopes/particular-drift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvasVideoExport.js
More file actions
275 lines (228 loc) · 7.34 KB
/
Copy pathcanvasVideoExport.js
File metadata and controls
275 lines (228 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
let projectName = "particles"; //to be updated
//detect user browser
var ua = navigator.userAgent;
var isSafari = false;
var isFirefox = false;
var isIOS = false;
var isAndroid = false;
if(ua.includes("Safari")){
isSafari = true;
}
if(ua.includes("Firefox")){
isFirefox = true;
}
if(ua.includes("iPhone") || ua.includes("iPad") || ua.includes("iPod")){
isIOS = true;
}
if(ua.includes("Android")){
isAndroid = true;
}
console.log("isSafari: "+isSafari+", isFirefox: "+isFirefox+", isIOS: "+isIOS+", isAndroid: "+isAndroid);
var mediaRecorder;
var recordedChunks;
var finishedBlob;
var recordingMessageDiv = document.getElementById("videoRecordingMessageDiv");
var recordVideoState = false;
var videoRecordInterval;
var videoEncoder;
var muxer;
var mobileRecorder;
var videofps = 30;
let bitrate = 16_000_000;
function saveImage() {
console.log("Export png image");
// Create a temporary canvas with the same dimensions
const tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
const tempContext = tempCanvas.getContext('2d', {
willReadFrequently: true,
alpha: false // Disable alpha to ensure solid background
});
// First, fill the temporary canvas with the current background color
//const [r, g, b] = WebGLUtils.hexToRGB(CONFIG.backgroundColor);
//tempContext.fillStyle = `rgb(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)})`;
tempContext.fillStyle = CONFIG.backgroundColor;
tempContext.fillRect(0, 0, canvas.width, canvas.height);
// Draw the WebGL canvas on top
tempContext.globalCompositeOperation = 'source-over';
drawScene(lastTime);
// Force a render frame to ensure latest content
gl.flush();
gl.finish();
tempContext.drawImage(canvas, 0, 0);
// Create download link
const link = document.createElement('a');
link.href = tempCanvas.toDataURL('image/png');
const date = new Date();
const filename = projectName + `_${date.toLocaleDateString()}_${date.toLocaleTimeString()}.png`;
link.download = filename;
link.click();
// Cleanup
tempCanvas.remove();
}
function toggleVideoRecord(){
if(recordVideoState == false){
recordVideoState = true;
chooseRecordingFunction();
} else {
recordVideoState = false;
chooseEndRecordingFunction();
}
}
function chooseRecordingFunction(){
safeRestartAnimation();
if(isIOS || isAndroid || isFirefox){
startMobileRecording();
}else {
recordVideoMuxer();
}
}
function chooseEndRecordingFunction(){
if(isIOS || isAndroid || isFirefox){
mobileRecorder.stop();
}else {
finalizeVideo();
}
}
//record html canvas element and export as mp4 video
//source: https://devtails.xyz/adam/how-to-save-html-canvas-to-mp4-using-web-codecs-api
async function recordVideoMuxer() {
console.log("start muxer video recording");
var videoWidth = Math.floor(canvas.width/2)*2;
var videoHeight = Math.floor(canvas.height/4)*4; //force a number which is divisible by 4
console.log("Video dimensions: "+videoWidth+", "+videoHeight);
//display user message
recordingMessageDiv.classList.remove("hidden");
recordVideoState = true;
const ctx = canvas.getContext("2d", {
// This forces the use of a software (instead of hardware accelerated) 2D canvas
// This isn't necessary, but produces quicker results
willReadFrequently: true,
// Desynchronizes the canvas paint cycle from the event loop
// Should be less necessary with OffscreenCanvas, but with a real canvas you will want this
desynchronized: true,
});
muxer = new Mp4Muxer.Muxer({
target: new Mp4Muxer.ArrayBufferTarget(),
video: {
// If you change this, make sure to change the VideoEncoder codec as well
codec: "avc",
width: videoWidth,
height: videoHeight,
},
firstTimestampBehavior: 'offset',
// mp4-muxer docs claim you should always use this with ArrayBufferTarget
fastStart: "in-memory",
});
videoEncoder = new VideoEncoder({
output: (chunk, meta) => muxer.addVideoChunk(chunk, meta),
error: (e) => console.error(e),
});
// This codec should work in most browsers
// See https://dmnsgn.github.io/media-codecs for list of codecs and see if your browser supports
videoEncoder.configure({
codec: "avc1.4d0032",
width: videoWidth,
height: videoHeight,
bitrate: bitrate,
bitrateMode: "variable",
});
//NEW codec: "avc1.4d0032",
//ORIGINAL codec: "avc1.42003e",
var frameNumber = 0;
//setTimeout(finalizeVideo,1000*videoDuration+200); //finish and export video after x seconds
//take a snapshot of the canvas every x miliseconds and encode to video
videoRecordInterval = setInterval(
function(){
if(recordVideoState == true){
drawScene(lastTime);
renderCanvasToVideoFrameAndEncode({
canvas,
videoEncoder,
frameNumber,
videofps
})
frameNumber++;
}else{
}
} , 1000/videofps);
}
//finish and export video
async function finalizeVideo(){
console.log("finalize muxer video");
togglePlayPause();
clearInterval(videoRecordInterval);
//playAnimationToggle = false;
recordVideoState = false;
// Forces all pending encodes to complete
await videoEncoder.flush();
muxer.finalize();
let buffer = muxer.target.buffer;
finishedBlob = new Blob([buffer]);
downloadBlob(new Blob([buffer]));
//hide user message
recordingMessageDiv.classList.add("hidden");
togglePlayPause();
}
async function renderCanvasToVideoFrameAndEncode({
canvas,
videoEncoder,
frameNumber,
videofps,
}) {
let frame = new VideoFrame(canvas, {
// Equally spaces frames out depending on frames per second
timestamp: (frameNumber * 1e6) / videofps,
});
// The encode() method of the VideoEncoder interface asynchronously encodes a VideoFrame
videoEncoder.encode(frame);
// The close() method of the VideoFrame interface clears all states and releases the reference to the media resource.
frame.close();
}
function downloadBlob() {
console.log("download video");
let url = window.URL.createObjectURL(finishedBlob);
let a = document.createElement("a");
a.style.display = "none";
a.href = url;
const date = new Date();
const filename = projectName+`_${date.toLocaleDateString()}_${date.toLocaleTimeString()}.mp4`;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
//record and download videos on mobile devices
function startMobileRecording(){
var stream = canvas.captureStream(videofps);
mobileRecorder = new MediaRecorder(stream, { 'type': 'video/mp4' });
mobileRecorder.addEventListener('dataavailable', finalizeMobileVideo);
console.log("start simple video recording");
console.log("Video dimensions: "+canvas.width+", "+canvas.height);
//display user message
//recordingMessageCountdown(videoDuration);
recordingMessageDiv.classList.remove("hidden");
recordVideoState = true;
mobileRecorder.start(); //start mobile video recording
/*
setTimeout(function() {
recorder.stop();
}, 1000*videoDuration+200);
*/
}
function finalizeMobileVideo(e) {
setTimeout(function(){
console.log("finish simple video recording");
togglePlayPause();
recordVideoState = false;
/*
mobileRecorder.stop();*/
var videoData = [ e.data ];
finishedBlob = new Blob(videoData, { 'type': 'video/mp4' });
downloadBlob(finishedBlob);
//hide user message
recordingMessageDiv.classList.add("hidden");
togglePlayPause();
},500);
}