@pexip/media-processor 16.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,188 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled
32
+ object code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work (an example is provided in the Appendix
37
+ below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as a
42
+ whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its
54
+ representatives, including but not limited to communication on electronic
55
+ mailing lists, source code control systems, and issue tracking systems that
56
+ are managed by, or on behalf of, the Licensor for the purpose of discussing
57
+ and improving the Work, but excluding communication that is conspicuously
58
+ marked or otherwise designated in writing by the copyright owner as "Not a
59
+ Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
62
+ behalf of whom a Contribution has been received by Licensor and subsequently
63
+ incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
66
+ License, each Contributor hereby grants to You a perpetual, worldwide,
67
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
68
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
69
+ sublicense, and distribute the Work and such Derivative Works in Source or
70
+ Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
73
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
74
+ no-charge, royalty-free, irrevocable (except as stated in this section)
75
+ patent license to make, have made, use, offer to sell, sell, import, and
76
+ otherwise transfer the Work, where such license applies only to those patent
77
+ claims licensable by such Contributor that are necessarily infringed by their
78
+ Contribution(s) alone or by combination of their Contribution(s) with the
79
+ Work to which such Contribution(s) was submitted. If You institute patent
80
+ litigation against any entity (including a cross-claim or counterclaim in a
81
+ lawsuit) alleging that the Work or a Contribution incorporated within the
82
+ Work constitutes direct or contributory patent infringement, then any patent
83
+ licenses granted to You under this License for that Work shall terminate as
84
+ of the date such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
87
+ Derivative Works thereof in any medium, with or without modifications, and in
88
+ Source or Object form, provided that You meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works a
91
+ copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices stating
94
+ that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works that You
97
+ distribute, all copyright, patent, trademark, and attribution notices from
98
+ the Source form of the Work, excluding those notices that do not pertain to
99
+ any part of the Derivative Works; and
100
+
101
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
102
+ then any Derivative Works that You distribute must include a readable copy
103
+ of the attribution notices contained within such NOTICE file, excluding
104
+ those notices that do not pertain to any part of the Derivative Works, in at
105
+ least one of the following places: within a NOTICE text file distributed as
106
+ part of the Derivative Works; within the Source form or documentation, if
107
+ provided along with the Derivative Works; or, within a display generated by
108
+ the Derivative Works, if and wherever such third-party notices normally
109
+ appear. The contents of the NOTICE file are for informational purposes only
110
+ and do not modify the License. You may add Your own attribution notices
111
+ within Derivative Works that You distribute, alongside or as an addendum to
112
+ the NOTICE text from the Work, provided that such additional attribution
113
+ notices cannot be construed as modifying the License.
114
+
115
+ You may add Your own copyright statement to Your modifications and may
116
+ provide additional or different license terms and conditions for use,
117
+ reproduction, or distribution of Your modifications, or for any such
118
+ Derivative Works as a whole, provided Your use, reproduction, and
119
+ distribution of the Work otherwise complies with the conditions stated in
120
+ this License.
121
+
122
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
123
+ Contribution intentionally submitted for inclusion in the Work by You to the
124
+ Licensor shall be under the terms and conditions of this License, without any
125
+ additional terms or conditions. Notwithstanding the above, nothing herein
126
+ shall supersede or modify the terms of any separate license agreement you may
127
+ have executed with Licensor regarding such Contributions.
128
+
129
+ 6. Trademarks. This License does not grant permission to use the trade names,
130
+ trademarks, service marks, or product names of the Licensor, except as
131
+ required for reasonable and customary use in describing the origin of the
132
+ Work and reproducing the content of the NOTICE file.
133
+
134
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
135
+ writing, Licensor provides the Work (and each Contributor provides its
136
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
137
+ KIND, either express or implied, including, without limitation, any
138
+ warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
139
+ FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining
140
+ the appropriateness of using or redistributing the Work and assume any risks
141
+ associated with Your exercise of permissions under this License.
142
+
143
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
144
+ tort (including negligence), contract, or otherwise, unless required by
145
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
146
+ in writing, shall any Contributor be liable to You for damages, including any
147
+ direct, indirect, special, incidental, or consequential damages of any
148
+ character arising as a result of this License or out of the use or inability
149
+ to use the Work (including but not limited to damages for loss of goodwill,
150
+ work stoppage, computer failure or malfunction, or any and all other
151
+ commercial damages or losses), even if such Contributor has been advised of
152
+ the possibility of such damages.
153
+
154
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
155
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
156
+ acceptance of support, warranty, indemnity, or other liability obligations
157
+ and/or rights consistent with this License. However, in accepting such
158
+ obligations, You may act only on Your own behalf and on Your sole
159
+ responsibility, not on behalf of any other Contributor, and only if You agree
160
+ to indemnify, defend, and hold each Contributor harmless for any liability
161
+ incurred by, or claims asserted against, such Contributor by reason of your
162
+ accepting any such warranty or additional liability.
163
+
164
+ END OF TERMS AND CONDITIONS
165
+
166
+ APPENDIX: How to apply the Apache License to your work.
167
+
168
+ To apply the Apache License to your work, attach the following
169
+ boilerplate notice, with the fields enclosed by brackets "[]"
170
+ replaced with your own identifying information. (Don't include
171
+ the brackets!) The text should be enclosed in the appropriate
172
+ comment syntax for the file format. We also recommend that a
173
+ file or class name and description of purpose be included on the
174
+ same "printed page" as the copyright notice for easier
175
+ identification within third-party archives.
176
+
177
+ Copyright 2023 Pexip AS
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
180
+ this file except in compliance with the License. You may obtain a copy of the
181
+ License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software distributed
186
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
187
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
188
+ specific language governing permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # Media Processor
2
+
3
+ An package for media data processing using Web API.
4
+
5
+ ## Documentation
6
+
7
+ - [Changelog](./CHANGELOG.md)
8
+
9
+ ## Examples
10
+
11
+ ### Use Analyzer to get the MediaStream data
12
+
13
+ ```typescript
14
+ const stream = await navigator.mediaDevices.getUserMedia({audio:true});
15
+
16
+ const fftSize = 64;
17
+ // Setup an Audio Graph with `source` -> `analyzer`
18
+ const source = createStreamSourceGraphNode(stream);
19
+ const analyzer = createAnalyzerGraphNode({fftSize});
20
+ const audioGraph = createAudioGraph([[source, analyzer]]);
21
+
22
+ // Grab the current time domain data in floating point representation
23
+ const buffer = new Float32Array(fftSize);
24
+ analyzer.node?.getFloatTimeDomainData(buffer);
25
+ // Do some work with the buffer
26
+ buffer.forEach(...);
27
+
28
+ // Get the current volume, [0, 1]
29
+ const volume = analyzer.getAverageVolume(buffer);
30
+
31
+ // Release the resources when you have done with the analyzer
32
+ await audioGraph.release();
33
+ ```
34
+
35
+ ### Use AudioGraph to control the audio gain to mute/unmute
36
+
37
+ ```typescript
38
+ const stream = await navigator.mediaDevices.getUserMedia({
39
+ audio: true,
40
+ video: true,
41
+ });
42
+
43
+ const mute = !stream.getAudioTracks()[0]?.enabled;
44
+
45
+ // Setup an Audio Graph with `source` -> `gain`
46
+ const source = createStreamSourceGraphNode(stream);
47
+ const gain = createGainGraphNode(mute);
48
+ const destination = createStreamDestinationGraphNode();
49
+
50
+ const audioGraph = createAudioGraph([[source, gain, destination]]);
51
+
52
+ // Use the output MediaStream to for the altered AudioTrack
53
+ const alteredStream = new MediaStream([
54
+ ...stream.getVideoTracks(),
55
+ ...destination.stream.getAudioTracks(),
56
+ ]);
57
+
58
+ // Mute the audio
59
+ if (gain.node) {
60
+ gain.node.mute = true;
61
+ }
62
+
63
+ // Check if the audio is muted
64
+ gain.node.mute; // returns `true`, since we have just set the gain to 0
65
+
66
+ // Release the resources when you have done with the analyzer
67
+ await audioGraph.release();
68
+ ```
69
+
70
+ ### Use noise suppression
71
+
72
+ ```typescript
73
+ const stream = await navigator.mediaDevices.getUserMedia({
74
+ audio: true,
75
+ video: true,
76
+ });
77
+
78
+ // Fetch denoise WebAssembly
79
+ const response = await fetch(
80
+ new URL('@pexip/denoise/denoise_bg.wasm', import.meta.url).href,
81
+ );
82
+ const wasmBuffer = await response.arrayBuffer();
83
+
84
+ // Setup an Audio Graph with `source` -> `gain`
85
+ const source = createStreamSourceGraphNode(stream);
86
+ const destination = createStreamDestinationGraphNode();
87
+
88
+ const audioGraph = createAudioGraph([[source, destination]]);
89
+ // Add worklet module
90
+ await audioGraph.addWorklet(
91
+ new URL(
92
+ '@pexip/media-processor/dist/worklets/denoise.worklet',
93
+ import.meta.url,
94
+ ).href
95
+ );
96
+ const denoise = createDenoiseWorkletGraphNode(wasmBuffer);
97
+ // Route the source through the denoise node
98
+ const audioGraph.connect([source, denoise, destination]);
99
+ const audioGraph.disconnect([source, destination]);
100
+
101
+ // Release the resources when you have done with the analyzer
102
+ await audioGraph.release();
103
+ ```
104
+
105
+ ### Use background blur
106
+
107
+ ```typescript
108
+ import {urls} from '@pexip/bg-blur';
109
+
110
+ const PROCESSING_WIDTH = 768;
111
+ const PROCESSING_HEIGHT = 432;
112
+
113
+ const stream = await navigator.mediaDevices.getUserMedia({video: true});
114
+
115
+ // Create symbolic link to link bg-blur/selfie_segmentation to a public folder
116
+ // Thus we can create a URL object to get the link to be used for the `gluePath`
117
+ const selfieJs = new URL(
118
+ `./selfie_segmentation/selfie_segmentation.js`,
119
+ document.baseURI,
120
+ );
121
+ const segmenter = createMediapipeSegmenter('selfie_segmentation', {
122
+ modelType: selfieModel,
123
+ processingWidth: PROCESSING_WIDTH,
124
+ processingHeight: PROCESSING_HEIGHT,
125
+ gluePath: selfieJs.href,
126
+ });
127
+
128
+ const transformer = createCanvasTransform(segmenter, {
129
+ effects: 'blur',
130
+ width: mediaState.width,
131
+ height: mediaState.height,
132
+ });
133
+
134
+ const getTrackProcessor = () => {
135
+ // Feature detection if the browser has the `MediaStreamProcessor` API
136
+ if ('MediaStreamTrackProcessor' in window) {
137
+ return processAPI === 'Streams API'
138
+ ? createVideoTrackProcessor() // Using the latest Streams API
139
+ : createVideoTrackProcessorWithFallback(); // Using the fallback implementation
140
+ }
141
+ return createVideoTrackProcessorWithFallback(); // Using the fallback implementation
142
+ };
143
+
144
+ const videoProcessor = createVideoProcessor([transformer], getTrackProcessor());
145
+
146
+ await videoProcessor.open();
147
+
148
+ // Passing the raw MediaStream to apply the effects
149
+ // Then, use the output stream for whatever purpose
150
+ const processedStream = await videoProcessor.process(stream);
151
+ ```
152
+
153
+ ### More examples
154
+
155
+ Please check the [Media Processor Demo](../../examples/media-processor-demo)
156
+
157
+ ## Profiling Web Audio
158
+
159
+ You can do it with chrome, [See here][profiling web audio].
160
+
161
+ ## How AudioWorkletNode and the AudioWorkletProcessor work together
162
+
163
+ ```
164
+ ┌─────────────────────────┐ ┌──────────────────────────┐
165
+ │ │ │ │
166
+ │ Main Global Scope │ │ AudioWorkletGlobalScope │
167
+ │ │ │ │
168
+ │ ┌───────────────────┐ │ │ ┌────────────────────┐ │
169
+ │ │ │ │ MessagePort │ │ │ │
170
+ │ │ AudioWorklet │◄─┼─────────────┼─►│ AudioWorklet │ │
171
+ │ │ Node │ │ │ │ Processor │ │
172
+ │ │ │ │ │ │ │ │
173
+ │ └───────────────────┘ │ │ └────────────────────┘ │
174
+ │ │ │ │
175
+ └─────────────────────────┘ └──────────────────────────┘
176
+ Main Thread WebAudio Render Thread
177
+ ```
178
+
179
+ ### Constraints when using the AudioWorklet
180
+
181
+ - Each `BaseAudioContext` possesses exactly one `AudioWorklet`
182
+ - 128 samples-frames
183
+ - No `fetch` API in the `AudioWorkletGlobalScope`
184
+ - No `TextEncoder/Decoder` APIs in the `AudioWorkletGlobalScope`
185
+
186
+ ## References
187
+
188
+ - [MDN - Web Audio API][web audio api]
189
+ - [Web Audio Spec][web audio spec]
190
+
191
+ [web audio api]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API
192
+ [web audio spec]: https://webaudio.github.io/web-audio-api
193
+ [profiling web audio]: https://web.dev/profiling-web-audio-apps-in-chrome