This repository has been archived by the owner on Jan 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
depthdemo.html
587 lines (493 loc) · 16.3 KB
/
depthdemo.html
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
<html>
<head>
</head>
<style>
body {
display: flex;
flex-direction: column;
font-family: 'Roboto', 'Noto', sans-serif;
line-height: 1.5;
background-color: #fbfbfb;
margin: 20px;
}
.select {
margin: 16px 0px;
display: flex;
flex-direction: column;
max-width: 400px;
}
select {
background-color: transparent;
width: 100%;
padding: 4px 0;
font-size: 16px;
color: rgba(0,0,0, 0.26);
border: none;
border-bottom: 1px solid rgba(0,0,0, 0.12);
}
select:focus {
outline: none;
}
.select > label {
font-size: 10pt;
color: gray;
}
#console {
color: red;
font-size: 150%;
}
canvas {
border: 1px solid #cccccd;
background-color: white;
}
#tabcontainer {
margin: 16px 0px;
}
#tabcontainer input {
height: 35px;
visibility: hidden;
}
label[for=tab1], label[for=tab2] {
color: gray;
cursor: pointer;
display: block;
float: left;
height, : 40px;
line-height: 40px;
margin-right: 5px;
padding: 0 20px;
text-align: center;
}
#tabcontainer input:hover + label {
background: lightgray;
color: gray;
}
#tabcontainer input:checked + label {
background: #f0f0f0;
color: dimgray;
position: relative;
z-index: 6;
}
#tabcontent1, #tabcontent2 {
background: #f0f0f0;
opacity: 0;
position: absolute;
z-index: -100;
}
#tabcontainer input#tab1:checked ~ #tabcontent #tabcontent1,
#tabcontainer input#tab2:checked ~ #tabcontent #tabcontent2 {
opacity: 1;
z-index: 100;
}
input.visible {
visibility: visible !important;
}
video-stream {
color: dimgray;
}
#synctab {
margin: 16px;
padding:0px;
color: dimgray;
}
label[for=synccanvas] {
display:block;
}
#show-background-video {
position: absolute;
bottom: 50px;
right: 25px;
color: gray;
z-index: 5;
height: 20px;
text-align: right;
}
#show-background-color {
position: absolute;
bottom: 30px;
right: 25px;
color: gray;
z-index: 5;
height: 20px;
text-align: right;
}
#show-video-toggle, #show-color-toggle {
visibility: visible !important;
height: 15px !important;
vertical-align:middle;
}
</style>
<template id="video-stream">
<style>
:host {
display: flex;
flex-flow: row wrap;
}
canvas {
align-self: center;
}
div {
margin: 16px;
}
label {
display: block;
}
</style>
<div>
<label>WebGL canvas with depth video frame texture:</label>
<canvas id="canvasGL" width="640" height="480"></canvas>
</div>
<div>
<label><input type="checkbox" onchange="readAndShowPixels(this)"></input>gl.readPixels and show in 2D canvas</label>
<canvas id="canvas2D" width="640" height="480"></canvas>
</div>
</template>
<body onload="onLoad()">
<h2>Depth Capture Demo</h2>
<div id="console">
<!-- Print error messages here. -->
</div>
<div class="select">
<label for="selectVideoDevice">Capture device with depth stream</label>
<select id="selectVideoDevice"></select>
</div>
<div id="tabcontainer">
<input id="tab1" type="radio" name="tabs" value="basic" checked="checked" data-ontaboff="stopBasicTab" data-ontabon="startBasicTab"/>
<label for="tab1">Render depth</label>
<input id="tab2" type="radio" name="tabs" value="sync" data-ontaboff="stopSyncTab" data-ontabon="startSyncTab"/>
<label for="tab2">Background removal</label>
<div id="tabcontent">
<div id = tabcontent1>
<video-stream></video-stream>
</div>
<div id="tabcontent2">
<div id="synctab">
<label for="synccanvas">Color stream is displayed over depth that is aligned to color:</label>
<div id="show-background-video">background video <input id="show-video-toggle" type="checkbox">
</div>
<div id="show-background-color">background color <input id="show-color-toggle" type="checkbox">
</div>
<canvas id="synccanvas" width="640px" height="480px"
style="background-color: black;">
</canvas>
</div>
</div>
</div>
</div>
</body>
<script src="depth-camera.js"></script>
<script src="depth-to-color-sync-render.js"></script>
<script>
let readAndShowDepthPixels = false;
let error = window.console.error;
window.console.error = (message, ...rest) => {
let target = document.querySelector('#console');
error.call(window.console, message, ...rest);
if (message instanceof Error) {
message = `${message.name}: ${message.message}`;
}
target.innerHTML += `${message}<br>`;
}
function readAndShowPixels(element) {
readAndShowDepthPixels = element.checked;
}
let tabs = document.getElementsByName("tabs");
let videos = {depth: null, color: null};
let syncrender = new DepthToColorSyncRender(document.querySelector("#synccanvas"));
let selectedtab = tabs[0];
for(let i = 0; i < tabs.length; i++) {
tabs[i].onclick = function() {
if(this !== selectedtab) {
window[selectedtab.dataset.ontaboff]();
selectedtab = this;
window[selectedtab.dataset.ontabon]();
}
};
}
function stopVideo(video) {
if (video && video.srcObject) {
const cs = video.srcObject;
for (let track of cs.getTracks()) {
track.stop();
}
video.srcObject = null;
}
}
function startBasicTab() {
const videoStreamEl = document.querySelector('video-stream');
videoStreamEl.play();
}
function stopBasicTab() {
const videoStreamEl = document.querySelector('video-stream');
videoStreamEl.pause();
}
async function startSyncTab() {
syncrender.setDepthVideo(videos.depth);
await syncrender.play();
videos.color = syncrender.colorVideo;
videos.depth = syncrender.depthVideo;
}
function stopSyncTab() {
syncrender.pause();
stopVideo(videos.color);
}
const videoToggle = document.getElementById("show-video-toggle");
const colorToggle = document.getElementById("show-color-toggle");
videoToggle.addEventListener("change", function() {
if (this.checked)
colorToggle.checked = false;
syncrender.showBackgroundColor(false);
syncrender.showBackgroundVideo(this.checked);
});
colorToggle.addEventListener("change", function() {
if (this.checked)
videoToggle.checked = false;
syncrender.showBackgroundVideo(false);
syncrender.showBackgroundColor(this.checked);
});
customElements.define('video-stream', class extends HTMLElement {
constructor() {
super();
const template = document.querySelector('#video-stream');
const clone = document.importNode(template.content, true);
const shadowRoot = this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(clone);
this._frameLoop = this._frameLoop.bind(this);
this.readBuffer = null;
this.readFormat = null;
}
connectedCallback() {
this.gl = this._configureGLContext();
const canvas = this.shadowRoot.getElementById("canvas2D");
this.ctx2d = canvas.getContext("2d");
this.frameAvailable = false;
this.video = this._createOffscreenVideo();
this.video.oncanplay = _ => { this.frameAvailable = true; }
this.video.addEventListener("play", this._frameLoop);
let hasTouchListeners = false;
const onVideoTouchStart = _ => {
hasTouchListeners = false;
window.removeEventListener("touchstart", onVideoTouchStart, true);
this.video.play();
}
if (this.video && this.video.paused && !hasTouchListeners) {
hasTouchListeners = true;
window.addEventListener("touchstart", onVideoTouchStart, true);
}
}
_createOffscreenVideo() {
return Object.assign(document.createElement("video"), {
autoplay: true,
loop: true,
crossOrigin: "anonymous",
width: 640,
height: 480
});
}
_frameLoop() {
const gl = this.gl;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, gl.depth_texture);
if (this.frameAvailable) {
// Upload the video frame to texture.
if (gl.color_buffer_float_ext) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, gl.RED, gl.FLOAT, this.video);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, gl.RGBA, gl.FLOAT, this.video);
}
if (readAndShowDepthPixels) {
// Read it back to buffer.
this._readPixels();
// TODO: process pixels.
// Put read and processed pixels to 2D canvas.
// Note: This is just one of scenarios for the demo. You can directly
// bind video to 2D canvas without using WebGL as intermediate step.
this._putReadPixelsTo2DCanvas();
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, gl.vertex_buffer);
gl.vertexAttribPointer(gl.vertex_location, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.index_buffer);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
if (!this.paused)
window.requestAnimationFrame(this._frameLoop);
}
pause() {
this.paused = true;
}
play() {
this.paused = false;
window.requestAnimationFrame(this._frameLoop);
}
_readPixels() {
const gl = this.gl;
// Bind the framebuffer the texture is color-attached to.
gl.bindFramebuffer(gl.FRAMEBUFFER, gl.framebuffer);
if (!this.readBuffer) {
this.readFormat = gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT);
if (this.readFormat == gl.RED && gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) == gl.FLOAT) {
this.readBuffer = new Float32Array(this.video.width * this.video.height);
} else {
this.readFormat = gl.RGBA;
this.readBuffer = new Float32Array(this.video.width * this.video.height * 4);
}
}
gl.readPixels(0, 0, this.video.width, this.video.height, this.readFormat, gl.FLOAT, this.readBuffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
_putReadPixelsTo2DCanvas() {
const img = this.ctx2d.getImageData(0, 0, this.video.width, this.video.height);
const data = img.data;
const stride = (this.readFormat === this.gl.RED) ? 1 : 4;
for (let i = 0, j = 0; i < data.length; i += 4, j += stride) {
data[i] = this.readBuffer[j] * 255;
data[i+3] = 255;
}
this.ctx2d.putImageData(img, 0, 0);
}
// Creates WebGL/WebGL2 context used to upload depth video to texture,
// read the pixels to Float buffer and optionElally render the texture.
_configureGLContext() {
const canvas = this.shadowRoot.getElementById("canvasGL");
const gl = canvas.getContext("webgl2");
if (gl) {
// The extension tells us if we can use single component R32F texture format.
gl.color_buffer_float_ext = gl.getExtension('EXT_color_buffer_float');
} else {
gl = canvas.getContext("webgl");
gl.getExtension("OES_texture_float");
}
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// Shaders and program are needed only if rendering depth texture.
var vertex_shader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertex_shader, `
attribute vec2 v;
varying vec2 t;
void main(){
gl_Position = vec4(v.x * 2.0 - 1.0, 1.0 - v.y * 2.0, 0, 1);
t = v;
}`);
gl.compileShader(vertex_shader);
var pixel_shader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(pixel_shader, `
precision mediump float;
uniform sampler2D s;
varying vec2 t;
void main(){
vec4 tex = texture2D(s, t) * vec4(10.0, 10.0, 10.0, 1.0);
gl_FragColor = tex.rrra;
}`);
gl.compileShader(pixel_shader);
var program = gl.createProgram();
gl.attachShader(program, vertex_shader);
gl.attachShader(program, pixel_shader);
gl.linkProgram(program);
gl.useProgram(program);
var vertex_location = gl.getAttribLocation(program, "v");
gl.enableVertexAttribArray(vertex_location);
gl.uniform1i(gl.getUniformLocation(program, "s"), 0);
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0,1,0,1,1,0,1]), gl.STATIC_DRAW);
var index_buffer= gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0,1,2,0,2,3]), gl.STATIC_DRAW);
var depth_texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, depth_texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
// Framebuffer for reading back the texture.
var framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, depth_texture, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.vertex_buffer = vertex_buffer;
gl.vertex_location = vertex_location;
gl.index_buffer = index_buffer;
gl.depth_texture = depth_texture;
gl.framebuffer = framebuffer;
return gl;
}
async loadStream(deviceId) {
stopVideo(videos.depth);
stopVideo(videos.color);
// If the item in drop-down list is selected, use it.
const getUserMedia = () => {
// add ?allow=all to URL to allow listing all devices (incl. those not supporting depth).
if (!deviceId && (new URL(window.location)).searchParams.get("allow") !== "all") {
return DepthCamera.getDepthStream();
}
const constraints = {
video: {
deviceId: deviceId ? { exact: deviceId } : {}
}
}
return navigator.mediaDevices.getUserMedia(constraints);
}
try {
const stream = await getUserMedia();
this.video.srcObject = stream;
videos.depth = this.video;
// Chrome, starting with version 59, implements getSettings() API.
const track = stream.getVideoTracks()[0];
if (track.getSettings) {
this.depthDeviceId = track.getSettings().deviceId;
}
} catch (err) {
console.error(err);
}
}
});
function populateSelectElement(devices) {
const selectEl = document.querySelector('#selectVideoDevice');
const videoStreamEl = document.querySelector('video-stream');
let selected = selectEl.value;
while (selectEl.firstChild) {
selectEl.removeChild(selectEl.firstChild);
}
let selectedDeviceStillExists = false;
for (let i = 0; i < devices.length; ++i) {
const info = devices[i];
if (info.kind !== 'videoinput') {
continue;
}
const optionEl = document.createElement('option');
optionEl.value = info.deviceId;
optionEl.text = info.label || 'camera ' + (selectEl.length + 1);
selectEl.appendChild(optionEl);
if (optionEl.value === selected) {
selectedDeviceStillExists = true;
}
}
if (selectedDeviceStillExists) {
selectEl.value = selected;
} else if (!selected) {
// If no other device is selected, set the initial selection to depth device.
if (videoStreamEl.depthDeviceId) {
selectEl.value = videoStreamEl.depthDeviceId;
}
}
}
function onLoad() {
const videoStreamEl = document.querySelector('video-stream');
const selectEl = document.querySelector('#selectVideoDevice');
selectEl.onchange = async event => {
selectEl.disabled = true;
const deviceId = event.target.value;
await videoStreamEl.loadStream(deviceId);
const devices = await navigator.mediaDevices.enumerateDevices();
populateSelectElement(devices);
if (selectedtab.value != "basic") {
// It is on by default; stop rendering it if not visible.
stopBasicTab();
}
window[selectedtab.dataset.ontabon]();
selectEl.disabled = false;
};
selectEl.dispatchEvent(new Event('change', { 'bubbles': true }))
}
</script>
</html>