-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
319 lines (253 loc) · 10.5 KB
/
main.js
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { FFmpeg } from '@ffmpeg/ffmpeg';
//import { FS } from '@ffmpeg/types';
import { toBlobURL, fetchFile } from '@ffmpeg/util';
import { CopyShader } from 'three/examples/jsm/shaders/CopyShader.js';
import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'
import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js'
// import { CanvasCapture } from 'canvas-capture';
import initJank from "./jank.js"
// ------------------------------Jank init--------------------------------- //
initJank();
// ------------------------------FFmpeg init------------------------------- //
const ffmpeg = new FFmpeg();
const baseURL = 'https://unpkg.com/@ffmpeg/[email protected]/dist/esm';
console.log("ffmpeg loading");
await ffmpeg.load({
coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
workerURL: await toBlobURL(`${baseURL}/ffmpeg-core.worker.js`, "text/javascript"),
});
ffmpeg.on("log", ({ type, message }) => { console.log(message) });
ffmpeg.on("progress", console.log);
console.log("ffmpeg loaded");
// ------------------------------3.js test scene--------------------------- //
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
renderer.xr.enabled = true;
document.body.appendChild(renderer.domElement);
const ambient = new THREE.AmbientLight(0x888888);
scene.add(ambient);
const light = new THREE.PointLight(0xd5deff, 100);
light.castShadow = true;
light.position.x = 5;
light.position.y = 0.5;
light.shadow.mapSize.width = 4096;
light.shadow.mapSize.height = 4096;
light.shadow.camera.near = 0.1;
light.shadow.camera.far = 50;
scene.add(light);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const cubeMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true;
cube.receiveShadow = true;
cube.position.y = 0.5;
scene.add(cube);
const sphereGeometry = new THREE.SphereGeometry(0.3, 64, 32);
const sphereMaterial = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.castShadow = true;
sphere.receiveShadow = true;
scene.add(sphere);
const sphereOrbitHeight = 3;
const sphereOrbitSpeed = 0.6;
sphere.position.add(cube.position);
sphere.position.add(new THREE.Vector3(0, 0, sphereOrbitHeight));
const octGeometry = new THREE.OctahedronGeometry(0.1);
const octMaterial = new THREE.MeshPhongMaterial({ color: 0x0000ff });
const oct = new THREE.Mesh(octGeometry, octMaterial);
oct.castShadow = true;
oct.receiveShadow = true;
scene.add(oct);
const octOrbitHeight = 1.0;
const octOrbitSpeed = 3.0;
oct.position.add(sphere.position);
oct.position.add(new THREE.Vector3(0, 0, octOrbitHeight));
const controls = new OrbitControls(camera, renderer.domElement);
controls.maxPolarAngle = 0.9 * Math.PI / 2;
const clock = new THREE.Clock();
let baseRenderTarget = new THREE.WebGLRenderTarget();
baseRenderTarget.setSize(window.innerWidth, window.innerHeight);
let copyRenderTarget = new THREE.WebGLRenderTarget(720, 720);
const copyMaterial = new THREE.ShaderMaterial(CopyShader);
copyMaterial.uniforms.tDiffuse.value = baseRenderTarget.texture;
const fsq = new FullScreenQuad(copyMaterial);
const recordingCanvas = document.createElement('canvas');
recordingCanvas.width = 720;
recordingCanvas.height = 720;
recordingCanvas.style.display = 'hidden';
document.body.appendChild(recordingCanvas);
// ---------------------Recording interface logic--------------------- //
let recording = false;
let saving = false;
let recordingStart = 0;
const frames = []
const frameTimes = []
function startVideoRecording() {
document.getElementById('record_button').innerText = "Stop recording";
frames.length = 0;
frameTimes.length = 0;
recordingStart = clock.getElapsedTime();
}
function stopVideoRecording() {
document.getElementById('record_button').innerText = "Start recording";
}
function setVideoRecording() {
if (!recording) {
stopVideoRecording();
} else {
startVideoRecording();
}
}
function toggleRecordingState() {
if (recording) recording = false;
else if (!saving) recording = true;
}
document.getElementById('record_button').addEventListener("click", toggleRecordingState, false);
document.getElementById('record_button').addEventListener("click", setVideoRecording, false);
async function JpegURLToFS(url, index) {
let data = dataUriToBytes(url);
await ffmpeg.writeFile(`${index}.jpg`, data);
}
async function RGBAToJpegFS(array, index) {
let data = array.slice();
await ffmpeg.writeFile(`${index}.raw`, data);
await ffmpeg.exec(["-f", "rawvideo", "-pix_fmt", "rgba", "-s", "720x720", "-i", `${index}.raw`, "-vcodec", "mjpeg", "-pix_fmt", "yuvj420p", `${index}.jpg`]);
}
function imgDataToCanvas() {
renderer.setRenderTarget(baseRenderTarget);
renderer.render(scene, camera);
renderer.setRenderTarget(copyRenderTarget);
fsq.render(renderer);
let buffer = new Uint8ClampedArray(720 * 720 * 4);
renderer.readRenderTargetPixels(copyRenderTarget, 0, 0, 720, 720, buffer);
let imgData = new ImageData(buffer, 720, 720);
recordingCanvas.getContext("2d").putImageData(imgData, 0, 0);
return recordingCanvas.toDataURL('image/jpeg');
}
async function jpegsMP3ToMP4(framerate, outputFilename) {
await ffmpeg.exec(["-r", framerate.toString(), "-f", "image2", "-i", "%d.jpg", "-i", "audio.mp3", "-vcodec", "libx264", "-acodec", "copy", "-pix_fmt", "yuv420p", outputFilename]);
}
var recordingMethod = imgDataToCanvas;
var frameProcessing = JpegURLToFS;
var videoProcessing = jpegsMP3ToMP4;
var audioBlob;
function initAudio(stream) {
const mediaRecorder = new MediaRecorder(stream);
const data = [];
mediaRecorder.ondataavailable = (event) => {
data.push(event.data);
};
mediaRecorder.onstop = (event) => {
audioBlob = data[0];
}
function setAudioRecording() {
if (recording) mediaRecorder.start();
else mediaRecorder.stop();
}
document.getElementById('record_button').addEventListener("click", setAudioRecording, false);
}
function audioFail(err) {
console.log(err);
}
navigator.getUserMedia({ audio: true }, initAudio, audioFail);
async function webmBlobToMP3FS() {
let data = await audioBlob.arrayBuffer();
await ffmpeg.writeFile("audio.webm", new Uint8Array(data));
await ffmpeg.exec(["-i", "audio.webm", "-vn", "-ab", "128k", "-ar", "44100", "-acodec", "libmp3lame", "audio.mp3"]);
}
var audioProcessing = webmBlobToMP3FS;
async function saveRecording(event) {
saving = true;
let framerate = event.currentTarget.framerate;
console.log("generating frames at " + framerate + "fps");
let urlCreator = window.URL || window.webkitURL;
let rateDuration = 1.0 / framerate;
let frameCount = 0;
let i = 0;
let duration = 0;
for (let i = 0; i < frameTimes.length; i++) {
while (frameTimes[i] > duration) {
await frameProcessing(frames[i], frameCount);
frameCount += 1;
duration += rateDuration;
}
}
console.log("processing audio");
await audioProcessing();
console.log("processing video");
await videoProcessing(framerate, "out.mp4");
console.log("reading video data");
const video_data = await ffmpeg.readFile("out.mp4");
console.log("updating video link");
document.getElementById('video_link').href = URL.createObjectURL(new Blob([video_data], { type: 'video/mp4' }));
document.getElementById('video_link').innerText = "Latest recording here";
saving = false;
}
document.getElementById('save_button').addEventListener("click", saveRecording, false);
document.getElementById('save_button').framerate = 60;
let lastElapsed = 0;
function animate() {
renderer.setAnimationLoop(render);
}
function render() {
let elapsed = clock.getElapsedTime();
let delta = elapsed - lastElapsed;
const sphereDistance = new THREE.Vector3().subVectors(sphere.position, cube.position);
const sphereMovement = new THREE.Vector3().crossVectors(sphereDistance, new THREE.Vector3(0, 1, 0));
sphereMovement.setLength(sphereOrbitSpeed * delta);
sphereDistance.add(sphereMovement);
sphereDistance.setLength(sphereOrbitHeight);
sphere.position.addVectors(cube.position, sphereDistance);
const octDistance = new THREE.Vector3().subVectors(oct.position, sphere.position);
const octMovement = new THREE.Vector3().crossVectors(octDistance, new THREE.Vector3(0, 1, 0));
octMovement.setLength(octOrbitSpeed * delta);
octDistance.add(octMovement);
octDistance.setLength(octOrbitHeight);
oct.position.addVectors(sphere.position, octDistance);
cube.rotation.x += 0.5 * delta;
cube.rotation.y += 0.5 * delta;
cube.rotation.z += 0.5 * delta;
oct.rotation.x += 0.5 * delta;
oct.rotation.y += 0.5 * delta;
oct.rotation.z += 0.5 * delta;
renderer.setRenderTarget(null);
renderer.render(scene, camera);
if (recording) {
frames.push(recordingMethod());
frameTimes.push(elapsed - recordingStart);
}
lastElapsed = elapsed;
}
// -------------------------------------- HELPERS FROM CONNOR ------------------------------------------ //
export const base64ToBytes = (dataString) => {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
const byteString = atob(dataString);
const l = byteString.length;
const data = new Uint8Array(new ArrayBuffer(l));
for (let i = 0; i < l; i++) {
data[i] = byteString.charCodeAt(i);
}
return data;
};
export const dataUriToBytes = (dataUri) => {
const split = dataUri.split(",")[1];
return base64ToBytes(split);
};
window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
baseRenderTarget.setSize(window.innerWidth, window.innerHeight);
};
animate();