forked from tidoust/media-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlackAndWhiteConverter.js
55 lines (49 loc) · 1.61 KB
/
BlackAndWhiteConverter.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
'use strict';
/**
* Returns a transformer for a TransformStream that converts an RGBX VideoFrame
* to shades of grey.
*
* The transformer uses pure JavaScript.
*/
function BlackAndWhiteConverter(config) {
// 4 bytes per pixel for RGBA/RGBX video frames
const frameSize = config.width * config.height * 4;
const buffer = new Uint8Array(frameSize);
return {
/**
* Process a new frame and replace colors it contains with grey.
*/
async transform(frame, controller) {
// Copy frame bytes to the buffer
await frame.copyTo(buffer);
// Process frame in JavaScript, converting colors to grey
// (using Y component of "YUV" formula: https://en.wikipedia.org/wiki/YUV)
for (let pos = 0; pos < frameSize; pos += 4) {
const shade = Math.round(
0.2126 * buffer[pos] +
0.7152 * buffer[pos+1] +
0.0722 * buffer[pos+2]
);
buffer[pos] = shade;
buffer[pos+1] = shade;
buffer[pos+2] = shade;
}
// Create new frame out of processed buffer
const processedFrame = new VideoFrame(buffer, {
format: frame.format,
codedWidth: frame.codedWidth,
codedHeight: frame.codedHeight,
timestamp: frame.timestamp,
duration: frame.duration,
visibleRect: frame.visibleRect,
displayWidth: frame.displayWidth,
displayHeight: frame.displayHeight,
colorSpace: frame.colorSpace
});
// Time to get rid of the incoming VideoFrame and to return the newly
// created one.
frame.close();
controller.enqueue(processedFrame);
}
};
}