forked from webrtc/samples
-
Notifications
You must be signed in to change notification settings - Fork 2
/
webgpu-background-blur.js
753 lines (672 loc) · 22.3 KB
/
webgpu-background-blur.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
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/*
* Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
const preprocessWGSL = `
struct Tensor {
values: array<f32>;
};
@group(0) @binding(0) var samp : sampler;
@group(0) @binding(1) var<storage, write> inputTensor : Tensor;
@group(0) @binding(2) var inputTex : texture_2d<f32>;
@stage(compute) @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) globalID : vec3<u32>) {
let dims : vec2<i32> = textureDimensions(inputTex, 0);
var inputValue = textureSampleLevel(inputTex, samp, vec2<f32>(globalID.xy) / vec2<f32>(dims), 0.0).rgb;
var normalizedInput = (inputValue * vec3<f32>(255.0, 255.0, 255.0) - vec3<f32>(127.5, 127.5, 127.5)) / vec3<f32>(127.5, 127.5, 127.5);
var inputX : u32 = u32(floor(f32(globalID.x) / f32(dims.x) * 513.0));
var inputY : u32 = u32(floor(f32(globalID.y) / f32(dims.y) * 513.0));
inputTensor.values[0u * 513u * 513u + globalID.y * 513u + globalID.x] = normalizedInput.r;
inputTensor.values[1u * 513u * 513u + globalID.y * 513u + globalID.x] = normalizedInput.g;
inputTensor.values[2u * 513u * 513u + globalID.y * 513u + globalID.x] = normalizedInput.b;
}
`;
const segmentationWGSL = `
struct SegMap {
labels: array<i32>;
};
@group(0) @binding(0) var samp : sampler;
@group(0) @binding(1) var<storage, read> segmap : SegMap;
@group(0) @binding(2) var inputTex : texture_2d<f32>;
@group(0) @binding(3) var blurredInputTex : texture_2d<f32>;
@group(0) @binding(4) var outputTex : texture_storage_2d<rgba8unorm, write>;
@stage(compute) @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) globalID : vec3<u32>) {
let dims : vec2<i32> = textureDimensions(inputTex, 0);
var input = textureSampleLevel(inputTex, samp, vec2<f32>(globalID.xy) / vec2<f32>(dims), 0.0).rgb;
var blurredInput = textureSampleLevel(blurredInputTex, samp, vec2<f32>(globalID.xy) / vec2<f32>(dims), 0.0).rgb;
var green : vec3<f32> = vec3<f32>(0.0, 1.0, 0.0);
var segmapX : u32 = u32(floor(f32(globalID.x) / f32(dims.x) * 513.0));
var segmapY : u32 = u32(floor(f32(globalID.y) / f32(dims.y) * 513.0));
var segmapIndex = segmapX + segmapY * 513u;
if (segmap.labels[segmapIndex] == 0) {
textureStore(outputTex, vec2<i32>(globalID.xy), vec4<f32>(blurredInput, 1.0));
} else {
textureStore(outputTex, vec2<i32>(globalID.xy), vec4<f32>(input, 1.0));
}
}
`;
const blurWGSL = `
struct Params {
filterDim : u32;
blockDim : u32;
};
@group(0) @binding(0) var samp : sampler;
@group(0) @binding(1) var<uniform> params : Params;
@group(1) @binding(1) var inputTex : texture_2d<f32>;
@group(1) @binding(2) var outputTex : texture_storage_2d<rgba8unorm, write>;
struct Flip {
value : u32;
};
@group(1) @binding(3) var<uniform> flip : Flip;
// This shader blurs the input texture in one direction, depending on whether
// |flip.value| is 0 or 1.
// It does so by running (128 / 4) threads per workgroup to load 128
// texels into 4 rows of shared memory. Each thread loads a
// 4 x 4 block of texels to take advantage of the texture sampling
// hardware.
// Then, each thread computes the blur result by averaging the adjacent texel values
// in shared memory.
// Because we're operating on a subset of the texture, we cannot compute all of the
// results since not all of the neighbors are available in shared memory.
// Specifically, with 128 x 128 tiles, we can only compute and write out
// square blocks of size 128 - (filterSize - 1). We compute the number of blocks
// needed in Javascript and dispatch that amount.
var<workgroup> tile : array<array<vec3<f32>, 128>, 4>;
@stage(compute) @workgroup_size(32, 1, 1)
fn main(
@builtin(workgroup_id) WorkGroupID : vec3<u32>,
@builtin(local_invocation_id) LocalInvocationID : vec3<u32>
) {
let filterOffset : u32 = (params.filterDim - 1u) / 2u;
let dims : vec2<i32> = textureDimensions(inputTex, 0);
let baseIndex = vec2<i32>(
WorkGroupID.xy * vec2<u32>(params.blockDim, 4u) +
LocalInvocationID.xy * vec2<u32>(4u, 1u)
) - vec2<i32>(i32(filterOffset), 0);
for (var r : u32 = 0u; r < 4u; r = r + 1u) {
for (var c : u32 = 0u; c < 4u; c = c + 1u) {
var loadIndex = baseIndex + vec2<i32>(i32(c), i32(r));
if (flip.value != 0u) {
loadIndex = loadIndex.yx;
}
tile[r][4u * LocalInvocationID.x + c] =
textureSampleLevel(inputTex, samp,
(vec2<f32>(loadIndex) + vec2<f32>(0.25, 0.25)) / vec2<f32>(dims), 0.0).rgb;
}
}
workgroupBarrier();
for (var r : u32 = 0u; r < 4u; r = r + 1u) {
for (var c : u32 = 0u; c < 4u; c = c + 1u) {
var writeIndex = baseIndex + vec2<i32>(i32(c), i32(r));
if (flip.value != 0u) {
writeIndex = writeIndex.yx;
}
let center : u32 = 4u * LocalInvocationID.x + c;
if (center >= filterOffset &&
center < 128u - filterOffset &&
all(writeIndex < dims)) {
var acc : vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);
for (var f : u32 = 0u; f < params.filterDim; f = f + 1u) {
var i : u32 = center + f - filterOffset;
acc = acc + (1.0 / f32(params.filterDim)) * tile[r][i];
}
textureStore(outputTex, writeIndex, vec4<f32>(acc, 1.0));
}
}
}
}
`;
const fullscreenTexturedQuadWGSL = `
@group(0) @binding(0) var mySampler : sampler;
@group(0) @binding(1) var myTexture : texture_2d<f32>;
struct VertexOutput {
@builtin(position) Position : vec4<f32>;
@location(0) fragUV : vec2<f32>;
};
@stage(vertex)
fn vert_main(@builtin(vertex_index) VertexIndex : u32) -> VertexOutput {
var pos = array<vec2<f32>, 6>(
vec2<f32>( 1.0, 1.0),
vec2<f32>( 1.0, -1.0),
vec2<f32>(-1.0, -1.0),
vec2<f32>( 1.0, 1.0),
vec2<f32>(-1.0, -1.0),
vec2<f32>(-1.0, 1.0));
var uv = array<vec2<f32>, 6>(
vec2<f32>(1.0, 0.0),
vec2<f32>(1.0, 1.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(1.0, 0.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(0.0, 0.0));
var output : VertexOutput;
output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);
output.fragUV = uv[VertexIndex];
return output;
}
@stage(fragment)
fn frag_main(@location(0) fragUV : vec2<f32>) -> @location(0) vec4<f32> {
return textureSample(myTexture, mySampler, fragUV);
}
`;
// Contants from the blur.wgsl shader.
const tileDim = 128;
const batch = [4, 4];
/**
* Segmentation using WebNN and applies a blur effect using WebGPU.
* @implements {FrameTransform} in pipeline.js
*/
class WebGPUBackgroundBlurTransform { // eslint-disable-line no-unused-vars
constructor(useWebNN = false) {
// All fields are initialized in init()
/** @private {?OffscreenCanvas} canvas used to render video frame */
this.canvas_ = null;
/** @private {string} */
this.debugPath_ = 'debug.pipeline.frameTransform_';
this.context_ = null;
this.device_ = null;
this.adapter_ = null;
this.blurSettings_ = {
filterSize: 15,
iterations: 2,
};
this.segmentationWidth_ = 513;
this.segmentationHeight_ = 513;
this.segmapBuffer_ = null;
this.deeplab_ = null;
this.useWebNN_ = useWebNN;
this.hasWebNN_ = true; // will check WebNN when init deeplab
this.isWorker_ = typeof DedicatedWorkerGlobalScope !== 'undefined' &&
globalThis instanceof DedicatedWorkerGlobalScope;
if (!this.isWorker_) {
this.blurBackgroundCheckbox_ = (/** @type {!HTMLInputElement} */ (
document.getElementById('segmentBackground')));
this.gui_ = null;
}
}
/** @override */
async init() {
console.log('[WebGPUBackgroundBlurTransform] Initializing WebGPU.');
if (!navigator.gpu) {
const msg = 'Failed to detect WebGPU. Check that WebGPU is supported ' +
'by your browser and hardware.';
if (this.isWorker_) {
postMessage({error: msg});
} else {
alert(msg);
}
return;
}
const adapter = await navigator.gpu.requestAdapter();
this.adapter_ = adapter;
await tf.setBackend('webgpu');
const device = tf.engine().backendInstance.device;
if (!device) {
throw new Error('Failed to create GPUDevice.');
}
this.device_ = device;
const canvas = new OffscreenCanvas(1, 1);
this.canvas_ = canvas;
const context = canvas.getContext('webgpu');
this.context_ = context;
const preprocessPipeline = device.createComputePipeline({
compute: {
module: device.createShaderModule({
code: preprocessWGSL,
}),
entryPoint: 'main',
},
});
this.preprocessPipeline_ = preprocessPipeline;
const segmentationPipeline = device.createComputePipeline({
compute: {
module: device.createShaderModule({
code: segmentationWGSL,
}),
entryPoint: 'main',
},
});
this.segmentationPipeline_ = segmentationPipeline;
const blurPipeline = device.createComputePipeline({
compute: {
module: device.createShaderModule({
code: blurWGSL,
}),
entryPoint: 'main',
},
});
this.blurPipeline_ = blurPipeline;
const presentationFormat = context.getPreferredFormat(adapter);
const fullscreenQuadPipeline = device.createRenderPipeline({
vertex: {
module: device.createShaderModule({
code: fullscreenTexturedQuadWGSL,
}),
entryPoint: 'vert_main',
},
fragment: {
module: device.createShaderModule({
code: fullscreenTexturedQuadWGSL,
}),
entryPoint: 'frag_main',
targets: [
{
format: presentationFormat,
},
],
},
primitive: {
topology: 'triangle-list',
},
});
this.fullscreenQuadPipeline_ = fullscreenQuadPipeline;
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
});
this.sampler_ = sampler;
const buffer0 = (() => {
const buffer = device.createBuffer({
size: 4,
mappedAtCreation: true,
usage: GPUBufferUsage.UNIFORM,
});
new Uint32Array(buffer.getMappedRange())[0] = 0;
buffer.unmap();
return buffer;
})();
this.buffer0_ = buffer0;
const buffer1 = (() => {
const buffer = device.createBuffer({
size: 4,
mappedAtCreation: true,
usage: GPUBufferUsage.UNIFORM,
});
new Uint32Array(buffer.getMappedRange())[0] = 1;
buffer.unmap();
return buffer;
})();
this.buffer1_ = buffer1;
const blurParamsBuffer = device.createBuffer({
size: 8,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM,
});
const computeConstants = device.createBindGroup({
layout: blurPipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: sampler,
},
{
binding: 1,
resource: {
buffer: blurParamsBuffer,
},
},
],
});
this.computeConstants_ = computeConstants;
const settings = this.blurSettings_;
let blockDim;
const updateSettings = () => {
blockDim = tileDim - (settings.filterSize - 1);
device.queue.writeBuffer(
blurParamsBuffer,
0,
new Uint32Array([settings.filterSize, blockDim])
);
};
if (!this.isWorker_) {
if (this.gui_) {
this.gui_.destroy();
}
this.gui_ = new dat.GUI();
this.gui_.add(settings, 'filterSize', 1, 33).step(2).onChange(updateSettings);
this.gui_.add(settings, 'iterations', 1, 10).step(1);
}
updateSettings();
const segmentationInputTexture = device.createTexture({
size: [this.segmentationWidth_, this.segmentationHeight_, 1],
format: 'rgba8unorm',
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
});
this.segmentationInputTexture_ = segmentationInputTexture;
const inputTensorBuffer = (() => {
const buffer = device.createBuffer({
size: 3 * this.segmentationWidth_ * this.segmentationHeight_ * Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE,
});
return buffer;
})();
this.inputTensorBuffer_ = inputTensorBuffer;
const segmapBuffer = (() => {
const buffer = device.createBuffer({
size: this.segmentationWidth_ * this.segmentationHeight_ * Uint32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE,
});
return buffer;
})();
this.segmapBuffer_ = segmapBuffer;
console.log(
'[WebGPUBackgroundBlurTransform] WebGPU initialized.', `${this.debugPath_}.canvas_ =`,
this.canvas_, `${this.debugPath_}.device_ =`, this.device_);
}
initResources_(frameWidth, frameHeight) {
const device = this.device_;
const cubeTexture = device.createTexture({
size: [frameWidth, frameHeight, 1],
format: 'rgba8unorm',
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
});
this.cubeTexture_ = cubeTexture;
const textures = [0, 1, 2].map(() => {
return device.createTexture({
size: {
width: frameWidth,
height: frameHeight,
},
format: 'rgba8unorm',
usage:
GPUTextureUsage.COPY_DST |
GPUTextureUsage.STORAGE_BINDING |
GPUTextureUsage.TEXTURE_BINDING,
});
});
this.textures_ = textures;
}
/** @override */
async transform(frame, controller) {
const device = this.device_;
const canvas = this.canvas_;
if (!device || !canvas) {
frame.close();
return;
}
const isSegmentBackground = this.isWorker_ ?
this.hasWebNN_ : (this.blurBackgroundCheckbox_.checked ? true : false);
// Set output size to input size
const frameWidth = frame.displayWidth;
const frameHeight = frame.displayHeight;
if (canvas.width !== frameWidth || canvas.height !== frameHeight) {
canvas.width = frameWidth;
canvas.height = frameHeight;
const devicePixelRatio = this.isWorker_ ? 1 : (window.devicePixelRatio || 1);
const presentationSize = [
canvas.width * devicePixelRatio,
canvas.height * devicePixelRatio,
];
const presentationFormat = this.context_.getPreferredFormat(this.adapter_);
this.context_.configure({
device: this.device_,
format: presentationFormat,
size: presentationSize,
});
this.initResources_(frameWidth, frameHeight);
}
let resultTensor = null;
let segmapBuffer = null;
if (isSegmentBackground) {
if (!this.deeplab_) {
if (this.useWebNN_) {
this.deeplab_ = new DeepLabV3MNV2Nchw()
this.hasWebNN_ = await this.deeplab_.init(this.device_);
if (!this.hasWebNN_) {
this.deeplab_ = null;
if (!this.isWorker_) {
this.blurBackgroundCheckbox_.checked = false;
}
}
} else {
let modelUrl = '../../../models/deeplab_pascal_1_default_1/model.json';
if (this.isWorker_) {
modelUrl = '../' + modelUrl;
}
this.deeplab_ = await tf.loadGraphModel(modelUrl);
console.log('DeepLab model loaded', this.deeplab_);
}
}
const resizedVideoBitmap = await createImageBitmap(
frame, {resizeWidth: this.segmentationWidth_, resizeHeight: this.segmentationHeight_});
if (this.useWebNN_) {
device.queue.copyExternalImageToTexture(
{ source: resizedVideoBitmap },
{ texture: this.segmentationInputTexture_ },
[this.segmentationWidth_, this.segmentationHeight_]
);
const preprocessBindGroup = device.createBindGroup({
layout: this.preprocessPipeline_.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: this.sampler_,
},
{
binding: 1,
resource: {
buffer: this.inputTensorBuffer_,
},
},
{
binding: 2,
resource: this.segmentationInputTexture_.createView(),
},
],
});
const commandEncoder = device.createCommandEncoder();
const computePass = commandEncoder.beginComputePass();
computePass.setPipeline(this.preprocessPipeline_);
computePass.setBindGroup(0, preprocessBindGroup);
computePass.dispatch(
Math.ceil(this.segmentationWidth_ / 8),
Math.ceil(this.segmentationHeight_ / 8)
);
computePass.end();
device.queue.submit([commandEncoder.finish()]);
this.deeplab_.compute(this.inputTensorBuffer_, this.segmapBuffer_);
segmapBuffer = this.segmapBuffer_;
} else {
// use TF.js WebGPU backend
resultTensor = tf.tidy(() => {
let inputTensor = tf.browser.fromPixels(resizedVideoBitmap);
const inputShape = inputTensor.shape;
inputShape.unshift(1);
inputTensor = inputTensor.reshape(inputShape);
return this.deeplab_.predict(inputTensor);
});
segmapBuffer = tf.engine().backendInstance.getBuffer(resultTensor.dataId);
}
resizedVideoBitmap.close();
}
// Upload video frame to texture
const videoBitmap = await createImageBitmap(frame);
device.queue.copyExternalImageToTexture(
{ source: videoBitmap },
{ texture: this.cubeTexture_ },
[frameWidth, frameHeight]
);
videoBitmap.close();
const externalResource = this.cubeTexture_.createView();
// Blur
const blurBindGroup0 = device.createBindGroup({
layout: this.blurPipeline_.getBindGroupLayout(1),
entries: [
{
binding: 1,
resource: externalResource,
},
{
binding: 2,
resource: this.textures_[0].createView(),
},
{
binding: 3,
resource: {
buffer: this.buffer0_,
},
},
],
});
const blurBindGroup1 = device.createBindGroup({
layout: this.blurPipeline_.getBindGroupLayout(1),
entries: [
{
binding: 1,
resource: this.textures_[0].createView(),
},
{
binding: 2,
resource: this.textures_[1].createView(),
},
{
binding: 3,
resource: {
buffer: this.buffer1_,
},
},
],
});
const blurBindGroup2 = device.createBindGroup({
layout: this.blurPipeline_.getBindGroupLayout(1),
entries: [
{
binding: 1,
resource: this.textures_[1].createView(),
},
{
binding: 2,
resource: this.textures_[0].createView(),
},
{
binding: 3,
resource: {
buffer: this.buffer0_,
},
},
],
});
const commandEncoder = device.createCommandEncoder();
const computePass = commandEncoder.beginComputePass();
computePass.setPipeline(this.blurPipeline_);
computePass.setBindGroup(0, this.computeConstants_);
const blockDim = tileDim - (this.blurSettings_.filterSize - 1);
computePass.setBindGroup(1, blurBindGroup0);
computePass.dispatch(
Math.ceil(frameWidth / blockDim),
Math.ceil(frameHeight / batch[1])
);
computePass.setBindGroup(1, blurBindGroup1);
computePass.dispatch(
Math.ceil(frameHeight / blockDim),
Math.ceil(frameWidth / batch[1])
);
for (let i = 0; i < this.blurSettings_.iterations - 1; ++i) {
computePass.setBindGroup(1, blurBindGroup2);
computePass.dispatch(
Math.ceil(frameWidth / blockDim),
Math.ceil(frameHeight / batch[1])
);
computePass.setBindGroup(1, blurBindGroup1);
computePass.dispatch(
Math.ceil(frameHeight / blockDim),
Math.ceil(frameWidth / batch[1])
);
}
if (isSegmentBackground) {
const segmentationBindBroup = device.createBindGroup({
layout: this.segmentationPipeline_.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: this.sampler_,
},
{
binding: 1,
resource: {
buffer: segmapBuffer,
},
},
{
binding: 2,
resource: externalResource,
},
{
binding: 3,
resource: this.textures_[0].createView(),
},
{
binding: 4,
resource: this.textures_[2].createView(),
},
],
});
computePass.setPipeline(this.segmentationPipeline_);
computePass.setBindGroup(0, segmentationBindBroup);
computePass.dispatch(
Math.ceil(frameWidth / 8),
Math.ceil(frameHeight / 8)
);
}
computePass.end();
const passEncoder = commandEncoder.beginRenderPass({
colorAttachments: [
{
view: this.context_.getCurrentTexture().createView(),
clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
loadOp: 'clear',
storeOp: 'store',
},
],
});
const showResultBindGroup = device.createBindGroup({
layout: this.fullscreenQuadPipeline_.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: this.sampler_,
},
{
binding: 1,
resource: isSegmentBackground ? this.textures_[2].createView() : this.textures_[0].createView(),
},
],
});
passEncoder.setPipeline(this.fullscreenQuadPipeline_);
passEncoder.setBindGroup(0, showResultBindGroup);
passEncoder.draw(6, 1, 0, 0);
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
await device.queue.onSubmittedWorkDone();
if (resultTensor) {
resultTensor.dispose();
}
// Create a video frame from canvas and enqueue it to controller
// alpha: 'discard' is needed in order to send frames to a PeerConnection.
frame.close();
controller.enqueue(new VideoFrame(this.canvas_, {timestamp: frame.timestamp, alpha: 'discard'}));
}
/** @override */
destroy() {
if (this.deeplab_) {
this.deeplab_.dispose();
}
this.deeplab_ = null;
if (!this.isWorker_) {
if (this.gui_) {
this.gui_.destroy();
}
}
this.gui_ = null;
}
}