初始化

This commit is contained in:
2025-07-30 13:39:32 +08:00
commit d1f2452b28
253 changed files with 32087 additions and 0 deletions

9
vendor/Broadway/AUTHORS vendored Normal file
View File

@@ -0,0 +1,9 @@
The following authors have all licensed their contributions to the project
under the licensing terms detailed in LICENSE.
Michael Bebenita <mbebenita@gmail.com>
Alon Zakai <alonzakai@gmail.com>
Andreas Gal <gal@mozilla.com>
Mathieu 'p01' Henri <mathieu@p01.org>
Matthias 'soliton4' Behrens <matthias.behrens@gmail.com>
Sam Leitch @oneam - provided the webgl canvas

6
vendor/Broadway/Decoder.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
declare class Avc {
public onPictureDecoded: (buffer: Uint8Array, width: number, height: number) => void;
public decode(data: Uint8Array): void;
}
export = Avc;

891
vendor/Broadway/Decoder.js vendored Normal file

File diff suppressed because one or more lines are too long

10
vendor/Broadway/LICENSE vendored Normal file
View File

@@ -0,0 +1,10 @@
Copyright (c) 2011, Project Authors (see AUTHORS file)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the names of the Project Authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

BIN
vendor/Broadway/avc.wasm.asset vendored Normal file

Binary file not shown.

204
vendor/Genymobile/scrcpy/LICENSE vendored Normal file
View File

@@ -0,0 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2018 Genymobile
Copyright (C) 2018-2021 Romain Vimont
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Binary file not shown.

22
vendor/h264-live-player/AUTHORS vendored Normal file
View File

@@ -0,0 +1,22 @@
The following authors have all licensed their contributions to the project
under the licensing terms detailed in LICENSE (MIT style)
# h264-live-player migration to TypeScript
* Sergey Volkov <drauggres@gmail.com>
# h264-live-player
* Francois Leurent @131 <131.js@cloudyks.org>
# Broadway emscriptend h264 (broadway/Decoder.js)
* Michael Bebenita <mbebenita@gmail.com>
* Alon Zakai <alonzakai@gmail.com>
* Andreas Gal <gal@mozilla.com>
* Mathieu 'p01' Henri <mathieu@p01.org>
* Matthias 'soliton4' Behrens <matthias.behrens@gmail.com>
# WebGL canvas helpers
* Sam Leitch @oneam
# AVC player inspiration
* Benjamin Xiao @urbenlegend

6
vendor/h264-live-player/Canvas.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
import Size from './utils/Size';
export default abstract class Canvas {
protected constructor(readonly canvas: HTMLCanvasElement, readonly size: Size) {}
public abstract decode(buffer: Uint8Array, width: number, height: number): void;
}

10
vendor/h264-live-player/LICENSE vendored Normal file
View File

@@ -0,0 +1,10 @@
Copyright (c) 2019, Project Authors (see AUTHORS file)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the names of the Project Authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

49
vendor/h264-live-player/Program.ts vendored Normal file
View File

@@ -0,0 +1,49 @@
import Shader from './Shader';
import assert from './utils/assert';
export default class Program {
public readonly program: WebGLProgram | null;
constructor(readonly gl: WebGLRenderingContext) {
this.program = this.gl.createProgram();
}
public attach(shader: Shader): void {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
if (!shader.shader) {
throw Error(`Shader type is ${typeof shader.shader}`);
}
this.gl.attachShader(this.program, shader.shader);
}
public link(): void {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
this.gl.linkProgram(this.program);
// If creating the shader program failed, alert.
assert(this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS),
'Unable to initialize the shader program.');
}
public use(): void {
this.gl.useProgram(this.program);
}
public getAttributeLocation(name: string): number {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
return this.gl.getAttribLocation(this.program, name);
}
public setMatrixUniform(name: string, array: Float32List): void {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
const uniform = this.gl.getUniformLocation(this.program, name);
this.gl.uniformMatrix4fv(uniform, false, array);
}
}

3
vendor/h264-live-player/README.md vendored Normal file
View File

@@ -0,0 +1,3 @@
Based on client code from [131/h264-live-player](https://github.com/131/h264-live-player/tree/6966af8/vendor)
See [License](LICENSE)

29
vendor/h264-live-player/Script.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
export default class Script {
constructor(public type: string, public source: string) {
}
public static createFromElementId(id: string): Script {
const script = document.getElementById(id);
// Didn't find an element with the specified ID, abort.
if (!script) {
throw Error('Could not find shader with ID: ' + id);
}
// Walk through the source element's children, building the shader source string.
let source = '';
let currentChild = script.firstChild;
while (currentChild) {
if (currentChild.nodeType === 3) {
source += currentChild.textContent;
}
currentChild = currentChild.nextSibling;
}
return new Script((script as HTMLScriptElement).type, source);
}
public static createFromSource(type: string, source: string): Script {
return new Script(type, source);
}
}

35
vendor/h264-live-player/Shader.ts vendored Normal file
View File

@@ -0,0 +1,35 @@
import Script from './Script';
import error from './utils/error';
export default class Shader {
public readonly shader?: WebGLShader | null;
constructor(readonly gl: WebGLRenderingContext, readonly script: Script) {
// Now figure out what type of shader script we have, based on its MIME type.
if (script.type === 'x-shader/x-fragment') {
this.shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (script.type === 'x-shader/x-vertex') {
this.shader = gl.createShader(gl.VERTEX_SHADER);
} else {
error(`Unknown shader type: ${script.type}`);
return;
}
if (!this.shader) {
error(`Shader is ${typeof this.shader}`);
return;
}
// Send the source to the shader object.
gl.shaderSource(this.shader, script.source);
// Compile the shader program.
gl.compileShader(this.shader);
// See if it compiled successfully.
if (!gl.getShaderParameter(this.shader, gl.COMPILE_STATUS)) {
error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(this.shader));
return;
}
}
}

61
vendor/h264-live-player/Texture.ts vendored Normal file
View File

@@ -0,0 +1,61 @@
import Size from './utils/Size';
import assert from './utils/assert';
import Program from './Program';
export default class Texture {
public readonly texture: WebGLTexture | null;
public readonly format: GLenum;
private textureIDs: number[];
static create (gl: WebGLRenderingContext, format: number): Texture {
return new Texture(gl, undefined, format);
}
constructor(readonly gl: WebGLRenderingContext, readonly size?: Size, format?: GLenum) {
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
this.format = format ? format : gl.LUMINANCE;
if (size) {
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, size.w, size.h, 0, this.format, gl.UNSIGNED_BYTE, null);
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this.textureIDs = [gl.TEXTURE0, gl.TEXTURE1, gl.TEXTURE2];
}
public fill(textureData: Uint8Array, useTexSubImage2D?: boolean, w?: number, h?: number): void {
if (typeof w === 'undefined' || typeof h === 'undefined') {
if (!this.size) {
return;
}
w = this.size.w;
h = this.size.h;
}
const gl = this.gl;
assert(textureData.length >= w * h,
'Texture size mismatch, data:' + textureData.length + ', texture: ' + w * h);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
if (useTexSubImage2D) {
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, this.format, gl.UNSIGNED_BYTE, textureData);
} else {
// texImage2D seems to be faster, thus keeping it as the default
gl.texImage2D(gl.TEXTURE_2D, 0, this.format, w, h, 0, this.format, gl.UNSIGNED_BYTE, textureData);
}
}
public image2dBuffer (buffer: Uint8Array, width: number, height: number) {
this.fill(buffer, false, width, height);
}
public bind(n: number, program: Program, name: string): void {
const gl = this.gl;
if (!program.program) {
return;
}
gl.activeTexture(this.textureIDs[n]);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.uniform1i(gl.getUniformLocation(program.program, name), n);
}
}

305
vendor/h264-live-player/WebGLCanvas.ts vendored Normal file
View File

@@ -0,0 +1,305 @@
import Size from './utils/Size';
import Texture from './Texture';
import error from './utils/error';
// @ts-ignore
import { Matrix, Vector } from 'sylvester.js';
import Program from './Program';
import Shader from './Shader';
import { makePerspective } from './utils/glUtils';
import Script from './Script';
import Canvas from './Canvas';
export default abstract class WebGLCanvas extends Canvas {
protected static vertexShaderScript: Script = Script.createFromSource('x-shader/x-vertex', `
attribute vec3 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
varying highp vec2 vTextureCoord;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
}
`);
protected static fragmentShaderScript: Script = Script.createFromSource('x-shader/x-fragment', `
precision highp float;
varying highp vec2 vTextureCoord;
uniform sampler2D texture;
void main(void) {
gl_FragColor = texture2D(texture, vTextureCoord);
}
`);
public quadVPBuffer?: WebGLBuffer | null;
public quadVTCBuffer?: WebGLBuffer | null;
public mvMatrix: Matrix;
public glNames?: Record<string, string>;
public textureCoordAttribute?: number;
public vertexPositionAttribute?: number;
public perspectiveMatrix: Matrix;
protected gl?: WebGLRenderingContext | null;
protected framebuffer?: WebGLFramebuffer | null;
protected framebufferTexture?: Texture;
protected texture?: Texture;
protected program?: Program;
constructor(readonly canvas: HTMLCanvasElement, readonly size: Size, useFrameBuffer: boolean) {
super(canvas, size);
this.canvas.width = size.w;
this.canvas.height = size.h;
this.onInitWebGL();
this.onInitShaders();
this.initBuffers();
if (useFrameBuffer) {
this.initFramebuffer();
}
this.onInitTextures();
this.initScene();
}
protected initFramebuffer(): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
// Create framebuffer object and texture.
this.framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
this.framebufferTexture = new Texture(gl, this.size, gl.RGBA);
// Create and allocate renderbuffer for depth data.
const renderbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.size.w, this.size.h);
// Attach texture and renderbuffer to the framebuffer.
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.framebufferTexture.texture, 0);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer);
}
protected initBuffers(): void {
let tmp;
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
// Create vertex position buffer.
this.quadVPBuffer = gl.createBuffer();
if (!this.quadVPBuffer) {
error(`quadVPBuffer type is ${typeof gl}`);
return;
}
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVPBuffer);
tmp = [
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(tmp), gl.STATIC_DRAW);
// (this.quadVPBuffer as any).itemSize = 3;
// (this.quadVPBuffer as any).numItems = 4;
/*
+--------------------+
| -1,1 (1) | 1,1 (0)
| |
| |
| |
| |
| |
| -1,-1 (3) | 1,-1 (2)
+--------------------+
*/
const scaleX = 1.0;
const scaleY = 1.0;
// Create vertex texture coordinate buffer.
this.quadVTCBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVTCBuffer);
tmp = [
scaleX, 0.0,
0.0, 0.0,
scaleX, scaleY,
0.0, scaleY
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(tmp), gl.STATIC_DRAW);
}
protected mvIdentity() : void {
this.mvMatrix = Matrix.I(4);
}
protected mvMultiply(m: number): void {
this.mvMatrix = this.mvMatrix.x(m);
}
protected mvTranslate(m: number[]): void {
const $V = Vector.create;
this.mvMultiply(Matrix.Translation($V([m[0], m[1], m[2]])).ensure4x4());
}
protected setMatrixUniforms(): void {
if (!this.program) {
error(`Program type is ${typeof this.program}`);
return;
}
this.program.setMatrixUniform('uPMatrix', new Float32Array(this.perspectiveMatrix.flatten()));
this.program.setMatrixUniform('uMVMatrix', new Float32Array(this.mvMatrix.flatten()));
}
protected initScene(): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
// Establish the perspective with which we want to view the
// scene. Our field of view is 45 degrees, with a width/height
// ratio of 640:480, and we only want to see objects between 0.1 units
// and 100 units away from the camera.
this.perspectiveMatrix = makePerspective(45, 1, 0.1, 100.0);
// Set the drawing position to the 'identity' point, which is
// the center of the scene.
this.mvIdentity();
// Now move the drawing position a bit to where we want to start
// drawing the square.
this.mvTranslate([0.0, 0.0, -2.4]);
// Draw the cube by binding the array buffer to the cube's vertices
// array, setting attributes, and pushing it to GL.
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVPBuffer as WebGLBuffer);
gl.vertexAttribPointer(this.vertexPositionAttribute as number, 3, gl.FLOAT, false, 0, 0);
// Set the texture coordinates attribute for the vertices.
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVTCBuffer as WebGLBuffer);
gl.vertexAttribPointer(this.textureCoordAttribute as number, 2, gl.FLOAT, false, 0, 0);
this.onInitSceneTextures();
this.setMatrixUniforms();
if (this.framebuffer) {
console.log('Bound Frame Buffer');
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
}
}
public toString(): string {
return 'WebGLCanvas Size: ' + this.size;
}
protected checkLastError(operation: string): void {
if (!this.gl || !this.glNames) {
return;
}
const err = this.gl.getError();
if (err !== this.gl.NO_ERROR) {
let name = this.glNames[err];
name = (name !== undefined) ? name + '(' + err + ')' :
('Unknown WebGL ENUM (0x' + err.toString(16) + ')');
if (operation) {
console.log('WebGL Error: %s, %s', operation, name);
} else {
console.log('WebGL Error: %s', name);
}
console.trace();
}
}
protected onInitWebGL(): void {
try {
this.gl = this.canvas.getContext('experimental-webgl', {
preserveDrawingBuffer: true
}) as WebGLRenderingContext;
} catch (e: any) {
}
if (!this.gl) {
error('Unable to initialize WebGL. Your browser may not support it.');
return;
}
if (this.glNames) {
return;
}
this.glNames = {};
for (const propertyName in this.gl) {
if (this.gl.hasOwnProperty(propertyName)) {
const value = (this.gl as unknown as Record<string, number>)[propertyName];
if (typeof value === 'number') {
this.glNames[value] = propertyName;
}
}
}
}
protected onInitShaders(): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
this.program = new Program(gl);
this.program.attach(new Shader(gl, WebGLCanvas.vertexShaderScript));
this.program.attach(new Shader(gl, WebGLCanvas.fragmentShaderScript));
this.program.link();
this.program.use();
this.vertexPositionAttribute = this.program.getAttributeLocation('aVertexPosition');
gl.enableVertexAttribArray(this.vertexPositionAttribute as number);
this.textureCoordAttribute = this.program.getAttributeLocation('aTextureCoord');
gl.enableVertexAttribArray(this.textureCoordAttribute as number);
}
protected onInitTextures(): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
this.texture = new Texture(gl, this.size, gl.RGBA);
}
protected onInitSceneTextures(): void {
if (!this.texture) {
error(`texture type is ${typeof this.texture}`);
return;
}
if (!this.program) {
error(`program type is ${typeof this.texture}`);
return;
}
this.texture.bind(0, this.program, 'texture');
}
protected drawScene(): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
protected readPixels(buffer: Uint8Array): void {
const gl = this.gl;
if (!gl) {
error(`gl type is ${typeof gl}`);
return;
}
gl.readPixels(0, 0, this.size.w, this.size.h, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
}
}

48
vendor/h264-live-player/YUVCanvas.ts vendored Normal file
View File

@@ -0,0 +1,48 @@
import Size from './utils/Size';
import Canvas from './Canvas';
export default class YUVCanvas extends Canvas {
private canvasCtx: CanvasRenderingContext2D;
private canvasBuffer: ImageData;
constructor(readonly canvas: HTMLCanvasElement, readonly size: Size) {
super(canvas, size);
this.canvasCtx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
this.canvasBuffer = this.canvasCtx.createImageData(size.w, size.h);
}
public decode(buffer: Uint8Array, width: number, height: number): void {
if (!buffer) {
return;
}
const lumaSize = width * height;
const chromaSize = lumaSize >> 2;
const ybuf = buffer.subarray(0, lumaSize);
const ubuf = buffer.subarray(lumaSize, lumaSize + chromaSize);
const vbuf = buffer.subarray(lumaSize + chromaSize, lumaSize + 2 * chromaSize);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const yIndex = x + y * width;
const uIndex = ~~(y / 2) * ~~(width / 2) + ~~(x / 2);
const vIndex = ~~(y / 2) * ~~(width / 2) + ~~(x / 2);
const R = 1.164 * (ybuf[yIndex] - 16) + 1.596 * (vbuf[vIndex] - 128);
const G = 1.164 * (ybuf[yIndex] - 16) - 0.813 * (vbuf[vIndex] - 128) - 0.391 * (ubuf[uIndex] - 128);
const B = 1.164 * (ybuf[yIndex] - 16) + 2.018 * (ubuf[uIndex] - 128);
const rgbIndex = yIndex * 4;
this.canvasBuffer.data[rgbIndex + 0] = R;
this.canvasBuffer.data[rgbIndex + 1] = G;
this.canvasBuffer.data[rgbIndex + 2] = B;
this.canvasBuffer.data[rgbIndex + 3] = 0xff;
}
}
this.canvasCtx.putImageData(this.canvasBuffer, 0, 0);
// const date = new Date();
// console.log('WSAvcPlayer: Decode time: ' + (date.getTime() - this.rcvtime) + ' ms');
}
}

View File

@@ -0,0 +1,120 @@
import WebGLCanvas from './WebGLCanvas';
import Size from './utils/Size';
import Program from './Program';
import Shader from './Shader';
import Script from './Script';
import Texture from './Texture';
export default class YUVWebGLCanvas extends WebGLCanvas {
protected static vertexShaderScript: Script = Script.createFromSource('x-shader/x-vertex', `
attribute vec3 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
varying highp vec2 vTextureCoord;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
}
`);
protected static fragmentShaderScript: Script = Script.createFromSource('x-shader/x-fragment', `
precision highp float;
varying highp vec2 vTextureCoord;
uniform sampler2D YTexture;
uniform sampler2D UTexture;
uniform sampler2D VTexture;
const mat4 YUV2RGB = mat4
(
1.1643828125, 0, 1.59602734375, -.87078515625,
1.1643828125, -.39176171875, -.81296875, .52959375,
1.1643828125, 2.017234375, 0, -1.081390625,
0, 0, 0, 1
);
void main(void) {
gl_FragColor = vec4(
texture2D(YTexture, vTextureCoord).x,
texture2D(UTexture, vTextureCoord).x,
texture2D(VTexture, vTextureCoord).x,
1
) * YUV2RGB;
}`);
private YTexture?: Texture;
private UTexture?: Texture;
private VTexture?: Texture;
constructor(readonly canvas: HTMLCanvasElement, readonly size: Size) {
super(canvas, size, false);
}
protected onInitShaders(): void {
if (!this.gl) {
return;
}
this.program = new Program(this.gl);
this.program.attach(new Shader(this.gl, YUVWebGLCanvas.vertexShaderScript));
this.program.attach(new Shader(this.gl, YUVWebGLCanvas.fragmentShaderScript));
this.program.link();
this.program.use();
this.vertexPositionAttribute = this.program.getAttributeLocation('aVertexPosition');
this.gl.enableVertexAttribArray(this.vertexPositionAttribute as number);
this.textureCoordAttribute = this.program.getAttributeLocation('aTextureCoord');
this.gl.enableVertexAttribArray(this.textureCoordAttribute as number);
}
protected onInitTextures(): void {
if (!this.gl) {
return;
}
this.YTexture = new Texture(this.gl, this.size);
this.UTexture = new Texture(this.gl, this.size.getHalfSize());
this.VTexture = new Texture(this.gl, this.size.getHalfSize());
}
protected onInitSceneTextures(): void {
if (!this.program) {
return;
}
if (!this.YTexture || !this.UTexture || !this.VTexture) {
return;
}
this.YTexture.bind(0, this.program, 'YTexture');
this.UTexture.bind(1, this.program, 'UTexture');
this.VTexture.bind(2, this.program, 'VTexture');
}
protected fillYUVTextures(y: Uint8Array, u: Uint8Array, v: Uint8Array): void {
if (!this.YTexture || !this.UTexture || !this.VTexture) {
return;
}
this.YTexture.fill(y);
this.UTexture.fill(u);
this.VTexture.fill(v);
}
public decode(buffer: Uint8Array, width: number, height: number): void {
if (!buffer) {
return;
}
if (!this.YTexture || !this.UTexture || !this.VTexture) {
return;
}
const lumaSize = width * height;
const chromaSize = lumaSize >> 2;
this.fillYUVTextures(
buffer.subarray(0, lumaSize),
buffer.subarray(lumaSize, lumaSize + chromaSize),
buffer.subarray(lumaSize + chromaSize, lumaSize + 2 * chromaSize)
);
this.drawScene();
}
public toString(): string {
return 'YUVCanvas Size: ' + this.size;
}
}

16
vendor/h264-live-player/utils/Size.ts vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* Represents a 2-dimensional size value.
*/
export default class Size {
constructor(public w: number, public h: number) {}
toString() {
return '(' + this.w + ', ' + this.h + ')';
}
getHalfSize() {
return new Size(this.w >>> 1, this.h >>> 1);
}
length() {
return this.w * this.h;
}
}

View File

@@ -0,0 +1,8 @@
import error from './error';
export default function assert(condition: boolean, message: string): void {
if (!condition) {
error(message);
throw new Error(message);
}
}

View File

@@ -0,0 +1,4 @@
export default function error(message: string): void {
console.error(message);
console.trace();
}

113
vendor/h264-live-player/utils/glUtils.ts vendored Normal file
View File

@@ -0,0 +1,113 @@
// @ts-ignore
import { Matrix, Vector } from 'sylvester.js';
const $M = Matrix.create;
// augment Sylvester some
Matrix.Translation = function(v: Matrix): Matrix {
if (v.elements.length === 2) {
const r = Matrix.I(3);
r.elements[2][0] = v.elements[0];
r.elements[2][1] = v.elements[1];
return r;
}
if (v.elements.length === 3) {
const r = Matrix.I(4);
r.elements[0][3] = v.elements[0];
r.elements[1][3] = v.elements[1];
r.elements[2][3] = v.elements[2];
return r;
}
throw Error('Invalid length for Translation');
};
Matrix.prototype.flatten = function(): number[] {
const result = [];
/* tslint:disable: no-invalid-this prefer-for-of */
if (this.elements.length === 0) {
return [];
}
for (let j = 0; j < this.elements[0].length; j++) {
for (let i = 0; i < this.elements.length; i++) {
result.push(this.elements[i][j]);
}
}
/* tslint:enable */
return result;
};
Matrix.prototype.ensure4x4 = function(): Matrix | null {
/* tslint:disable: no-invalid-this */
if (this.elements.length === 4 && this.elements[0].length === 4) {
return this;
}
if (this.elements.length > 4 || this.elements[0].length > 4) {
return null;
}
for (let i = 0; i < this.elements.length; i++) {
for (let j = this.elements[i].length; j < 4; j++) {
if (i === j) {
this.elements[i].push(1);
} else {
this.elements[i].push(0);
}
}
}
for (let i = this.elements.length; i < 4; i++) {
if (i === 0) {
this.elements.push([1, 0, 0, 0]);
} else if (i === 1) {
this.elements.push([0, 1, 0, 0]);
} else if (i === 2) {
this.elements.push([0, 0, 1, 0]);
} else if (i === 3) {
this.elements.push([0, 0, 0, 1]);
}
}
return this;
/* tslint:enable */
};
Vector.prototype.flatten = function(): number[] {
/* tslint:disable: no-invalid-this */
return this.elements;
/* tslint:enable */
};
//
// gluPerspective
//
export function makePerspective(fovy: number, aspect: number, znear: number, zfar: number): Matrix {
const ymax = znear * Math.tan(fovy * Math.PI / 360.0);
const ymin = -ymax;
const xmin = ymin * aspect;
const xmax = ymax * aspect;
return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
}
//
// glFrustum
//
function makeFrustum(left: number, right: number,
bottom: number, top: number,
znear: number, zfar: number): Matrix {
const X = 2 * znear / (right - left);
const Y = 2 * znear / (top - bottom);
const A = (right + left) / (right - left);
const B = (top + bottom) / (top - bottom);
const C = -(zfar + znear) / (zfar - znear);
const D = -2 * zfar * znear / (zfar - znear);
return $M([[X, 0, A, 0],
[0, Y, B, 0],
[0, 0, C, D],
[0, 0, -1, 0]]);
}

4
vendor/tinyh264/Canvas.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
export default abstract class Canvas {
constructor(protected readonly canvas: HTMLCanvasElement) {}
public abstract decode(buffer: Uint8Array, width: number, height: number): void;
}

View File

@@ -0,0 +1,3 @@
import { init } from 'tinyh264';
init();

13
vendor/tinyh264/LICENSE vendored Normal file
View File

@@ -0,0 +1,13 @@
Copyright (c) 2019 Erik De Rijcke
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

3
vendor/tinyh264/README.md vendored Normal file
View File

@@ -0,0 +1,3 @@
Based on demo code from [udevbe/tinyh264](https://github.com/udevbe/tinyh264/tree/caf7142/demo)
See [License](LICENSE)

39
vendor/tinyh264/ShaderCompiler.ts vendored Normal file
View File

@@ -0,0 +1,39 @@
/**
* Represents a WebGL shader object and provides a mechanism to load shaders from HTML
* script tags.
*/
export default class ShaderCompiler {
/**
* @param {WebGLRenderingContext}gl
* @param {{type: string, source: string}}script
* @return {WebGLShader}
*/
static compile(gl: WebGLRenderingContext, script: { type: string; source: string }): WebGLShader | null {
let shader: WebGLShader | null;
// Now figure out what type of shader script we have, based on its MIME type.
if (script.type === 'x-shader/x-fragment') {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (script.type === 'x-shader/x-vertex') {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
throw new Error('Unknown shader type: ' + script.type);
}
if (!shader) {
throw new Error('Failed to create shader');
}
// Send the source to the shader object.
gl.shaderSource(shader, script.source);
// Compile the shader program.
gl.compileShader(shader);
// See if it compiled successfully.
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
}
return shader;
}
}

64
vendor/tinyh264/ShaderProgram.ts vendored Normal file
View File

@@ -0,0 +1,64 @@
export default class ShaderProgram {
public program: WebGLProgram | null;
/**
* @param {WebGLRenderingContext}gl
*/
constructor(private gl: WebGLRenderingContext) {
this.program = this.gl.createProgram();
}
/**
* @param {WebGLShader}shader
*/
attach(shader: WebGLShader): void {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
this.gl.attachShader(this.program, shader);
}
link(): void {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
this.gl.linkProgram(this.program);
// If creating the shader program failed, alert.
if (!this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS)) {
console.error('Unable to initialize the shader program.');
}
}
use(): void {
this.gl.useProgram(this.program);
}
/**
* @param {string}name
* @return {number}
*/
getAttributeLocation(name: string): number {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
return this.gl.getAttribLocation(this.program, name);
}
/**
* @param {string}name
* @return {WebGLUniformLocation | null}
*/
getUniformLocation(name: string): WebGLUniformLocation | null {
if (!this.program) {
throw Error(`Program type is ${typeof this.program}`);
}
return this.gl.getUniformLocation(this.program, name);
}
/**
* @param {WebGLUniformLocation}uniformLocation
* @param {Array<number>}array
*/
setUniformM4(uniformLocation: WebGLUniformLocation, array: number[]): void {
this.gl.uniformMatrix4fv(uniformLocation, false, array);
}
}

50
vendor/tinyh264/ShaderSources.ts vendored Normal file
View File

@@ -0,0 +1,50 @@
/**
* @type {{type: string, source: string}}
*/
export const vertexQuad = {
type: 'x-shader/x-vertex',
source: `
precision mediump float;
uniform mat4 u_projection;
attribute vec2 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main(){
v_texCoord = a_texCoord;
gl_Position = u_projection * vec4(a_position, 0.0, 1.0);
}
`,
};
/**
* @type {{type: string, source: string}}
*/
export const fragmentYUV = {
type: 'x-shader/x-fragment',
source: `
precision lowp float;
varying vec2 v_texCoord;
uniform sampler2D yTexture;
uniform sampler2D uTexture;
uniform sampler2D vTexture;
const mat4 conversion = mat4(
1.0, 0.0, 1.402, -0.701,
1.0, -0.344, -0.714, 0.529,
1.0, 1.772, 0.0, -0.886,
0.0, 0.0, 0.0, 0.0
);
void main(void) {
float yChannel = texture2D(yTexture, v_texCoord).x;
float uChannel = texture2D(uTexture, v_texCoord).x;
float vChannel = texture2D(vTexture, v_texCoord).x;
vec4 channels = vec4(yChannel, uChannel, vChannel, 1.0);
vec3 rgb = (channels * conversion).xyz;
gl_FragColor = vec4(rgb, 1.0);
}
`,
};

45
vendor/tinyh264/YUVCanvas.ts vendored Normal file
View File

@@ -0,0 +1,45 @@
import Canvas from './Canvas';
export default class YUVCanvas extends Canvas {
private canvasCtx: CanvasRenderingContext2D;
private canvasBuffer: ImageData | null = null;
constructor(canvas: HTMLCanvasElement) {
super(canvas);
this.canvasCtx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
}
public decode(buffer: Uint8Array, width: number, height: number): void {
if (!buffer) {
return;
}
if (!this.canvasBuffer) {
this.canvasBuffer = this.canvasCtx.createImageData(width, height);
}
const lumaSize = width * height;
const chromaSize = lumaSize >> 2;
const ybuf = buffer.subarray(0, lumaSize);
const ubuf = buffer.subarray(lumaSize, lumaSize + chromaSize);
const vbuf = buffer.subarray(lumaSize + chromaSize, lumaSize + 2 * chromaSize);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const yIndex = x + y * width;
const uIndex = ~~(y / 2) * ~~(width / 2) + ~~(x / 2);
const vIndex = ~~(y / 2) * ~~(width / 2) + ~~(x / 2);
const R = 1.164 * (ybuf[yIndex] - 16) + 1.596 * (vbuf[vIndex] - 128);
const G = 1.164 * (ybuf[yIndex] - 16) - 0.813 * (vbuf[vIndex] - 128) - 0.391 * (ubuf[uIndex] - 128);
const B = 1.164 * (ybuf[yIndex] - 16) + 2.018 * (ubuf[uIndex] - 128);
const rgbIndex = yIndex * 4;
this.canvasBuffer.data[rgbIndex + 0] = R;
this.canvasBuffer.data[rgbIndex + 1] = G;
this.canvasBuffer.data[rgbIndex + 2] = B;
this.canvasBuffer.data[rgbIndex + 3] = 0xff;
}
}
this.canvasCtx.putImageData(this.canvasBuffer, 0, 0);
}
}

145
vendor/tinyh264/YUVSurfaceShader.ts vendored Normal file
View File

@@ -0,0 +1,145 @@
import ShaderProgram from './ShaderProgram';
import ShaderCompiler from './ShaderCompiler';
import { fragmentYUV, vertexQuad } from './ShaderSources';
import Texture from '../h264-live-player/Texture';
type ShaderArguments = {
yTexture: WebGLUniformLocation | null;
uTexture: WebGLUniformLocation | null;
vTexture: WebGLUniformLocation | null;
u_projection: WebGLUniformLocation | null;
a_position: number;
a_texCoord: number;
};
export default class YUVSurfaceShader {
/**
*
* @param {WebGLRenderingContext} gl
* @returns {YUVSurfaceShader}
*/
static create(gl: WebGLRenderingContext): YUVSurfaceShader {
const program = this._initShaders(gl);
const shaderArgs = this._initShaderArgs(gl, program);
const vertexBuffer = this._initBuffers(gl);
return new YUVSurfaceShader(gl, vertexBuffer as WebGLBuffer, shaderArgs, program);
}
static _initShaders(gl: WebGLRenderingContext): ShaderProgram {
const program = new ShaderProgram(gl);
program.attach(ShaderCompiler.compile(gl, vertexQuad) as WebGLShader);
program.attach(ShaderCompiler.compile(gl, fragmentYUV) as WebGLShader);
program.link();
program.use();
return program;
}
static _initShaderArgs(gl: WebGLRenderingContext, program: ShaderProgram): ShaderArguments {
// find shader arguments
const shaderArgs: ShaderArguments = {
yTexture: program.getUniformLocation('yTexture'),
uTexture: program.getUniformLocation('uTexture'),
vTexture: program.getUniformLocation('vTexture'),
u_projection: program.getUniformLocation('u_projection'),
a_position: program.getAttributeLocation('a_position'),
a_texCoord: program.getAttributeLocation('a_texCoord'),
};
gl.enableVertexAttribArray(shaderArgs.a_position);
gl.enableVertexAttribArray(shaderArgs.a_texCoord);
return shaderArgs;
}
static _initBuffers(gl: WebGLRenderingContext): WebGLBuffer | null {
// Create vertex buffer object.
return gl.createBuffer();
}
constructor(
private gl: WebGLRenderingContext,
private vertexBuffer: WebGLBuffer,
private shaderArgs: ShaderArguments,
private program: ShaderProgram,
) {}
/**
*
* @param {Texture} textureY
* @param {Texture} textureU
* @param {Texture} textureV
*/
setTexture(textureY: Texture, textureU: Texture, textureV: Texture): void {
const gl = this.gl;
gl.uniform1i(this.shaderArgs.yTexture, 0);
gl.uniform1i(this.shaderArgs.uTexture, 1);
gl.uniform1i(this.shaderArgs.vTexture, 2);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, textureY.texture);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textureU.texture);
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, textureV.texture);
}
use(): void {
this.program.use();
}
release(): void {
this.gl.useProgram(null);
}
/**
* @param {{w:number, h:number}}encodedFrameSize
* @param {{maxXTexCoord:number, maxYTexCoord:number}} h264RenderState
*/
updateShaderData(
encodedFrameSize: { w: number; h: number },
h264RenderState: { maxXTexCoord: number; maxYTexCoord: number },
): void {
const { w, h } = encodedFrameSize;
this.gl.viewport(0, 0, w, h);
// prettier-ignore
this.program.setUniformM4(this.shaderArgs.u_projection as WebGLUniformLocation, [
2.0 / w, 0, 0, 0,
0, 2.0 / -h, 0, 0,
0, 0, 1, 0,
-1, 1, 0, 1
])
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertexBuffer);
// prettier-ignore
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array([
// First triangle
// top left:
0, 0, 0, 0,
// top right:
w, 0, h264RenderState.maxXTexCoord, 0,
// bottom right:
w, h, h264RenderState.maxXTexCoord, h264RenderState.maxYTexCoord,
// Second triangle
// bottom right:
w, h, h264RenderState.maxXTexCoord, h264RenderState.maxYTexCoord,
// bottom left:
0, h, 0, h264RenderState.maxYTexCoord,
// top left:
0, 0, 0, 0
]), this.gl.DYNAMIC_DRAW);
this.gl.vertexAttribPointer(this.shaderArgs.a_position, 2, this.gl.FLOAT, false, 16, 0);
this.gl.vertexAttribPointer(this.shaderArgs.a_texCoord, 2, this.gl.FLOAT, false, 16, 8);
}
draw(): void {
const gl = this.gl;
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 6);
gl.bindTexture(gl.TEXTURE_2D, null);
}
}

66
vendor/tinyh264/YUVWebGLCanvas.ts vendored Normal file
View File

@@ -0,0 +1,66 @@
/**
* based on tinyh264 demo: https://github.com/udevbe/tinyh264/tree/master/demo
*/
import YUVSurfaceShader from './YUVSurfaceShader';
import Texture from '../h264-live-player/Texture';
import Canvas from './Canvas';
export default class YUVWebGLCanvas extends Canvas {
private yTexture: Texture;
private uTexture: Texture;
private vTexture: Texture;
private yuvSurfaceShader: YUVSurfaceShader;
constructor(canvas: HTMLCanvasElement) {
super(canvas);
const gl = canvas.getContext('experimental-webgl', {
preserveDrawingBuffer: true,
}) as WebGLRenderingContext | null;
if (!gl) {
throw new Error('Unable to initialize WebGL. Your browser may not support it.');
}
this.yuvSurfaceShader = YUVSurfaceShader.create(gl);
this.yTexture = Texture.create(gl, gl.LUMINANCE);
this.uTexture = Texture.create(gl, gl.LUMINANCE);
this.vTexture = Texture.create(gl, gl.LUMINANCE);
}
decode(buffer: Uint8Array, width: number, height: number): void {
this.canvas.width = width;
this.canvas.height = height;
// the width & height returned are actually padded, so we have to use the frame size to get the real image dimension
// when uploading to texture
const stride = width; // stride
// height is padded with filler rows
// if we knew the size of the video before encoding, we could cut out the black filler pixels. We don't, so just set
// it to the size after encoding
const sourceWidth = width;
const sourceHeight = height;
const maxXTexCoord = sourceWidth / stride;
const maxYTexCoord = sourceHeight / height;
const lumaSize = stride * height;
const chromaSize = lumaSize >> 2;
const yBuffer = buffer.subarray(0, lumaSize);
const uBuffer = buffer.subarray(lumaSize, lumaSize + chromaSize);
const vBuffer = buffer.subarray(lumaSize + chromaSize, lumaSize + 2 * chromaSize);
const chromaHeight = height >> 1;
const chromaStride = stride >> 1;
// we upload the entire image, including stride padding & filler rows. The actual visible image will be mapped
// from texture coordinates as to crop out stride padding & filler rows using maxXTexCoord and maxYTexCoord.
this.yTexture.image2dBuffer(yBuffer, stride, height);
this.uTexture.image2dBuffer(uBuffer, chromaStride, chromaHeight);
this.vTexture.image2dBuffer(vBuffer, chromaStride, chromaHeight);
this.yuvSurfaceShader.setTexture(this.yTexture, this.uTexture, this.vTexture);
this.yuvSurfaceShader.updateShaderData({ w: width, h: height }, { maxXTexCoord, maxYTexCoord });
this.yuvSurfaceShader.draw();
}
}