@pexip/media 16.7.1

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,350 @@
1
+ # `@pexip/media`
2
+
3
+ A package to connect `@pexip/media-control` and `@pexip/media-processor` to
4
+ create a streamlined media process
5
+
6
+ ## Overview
7
+
8
+ ### `createMedia`
9
+
10
+ It create an object to interact with the media stream, which is usually used for
11
+ our main stream.
12
+
13
+ Its majority features:
14
+
15
+ - Create a media pipeline to get and process the `MediaStream`, see
16
+ `createMediaPipeline`. It also provides some media features including:
17
+
18
+ - Video Processing - background blur
19
+ - Audio Processing - Noise Suppression
20
+ - Audio Signal Detection - To detect if the active audio input device capturing any audio
21
+ - Voice Activity Detection - To detect if there is any voice activity
22
+
23
+ - Provide media input related information
24
+ - Verify if we need to request a new `MediaStream`, see `updateMedia`
25
+ - Subscribe events from `@pexip/media-control` and update the state accordingly
26
+
27
+ ### `createAudioStreamProcess`
28
+
29
+ A processor to process audio from the stream to be used together with
30
+ `createMedia` as one of the media processor of the pipeline.
31
+
32
+ ### `createVideoStreamProcess`
33
+
34
+ A processor to process video from the stream to be used together with
35
+ `createMedia` as one of the media processor of the pipeline.
36
+
37
+ ### `createPreviewController`
38
+
39
+ It create an object to control the provided media stream, e.g. change the
40
+ audio/video input device and apply changes to main stream when necessary.
41
+
42
+ ## Usage
43
+
44
+ The package tries to follow the
45
+ [MediaStream API's Constraints pattern](https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints).
46
+ Beside the
47
+ [MediaTrackConstraintSet](https://w3c.github.io/mediacapture-main/#dictionary-mediatrackconstraints-members)
48
+ that's specified from the
49
+ [Media Capture and Streams](https://w3c.github.io/mediacapture-main) spec, we
50
+ have extended some additional media features as the following:
51
+
52
+ - Able to pass `MediaDeviceInfo` directly to audio/video
53
+ - Add `vad` to use our own implementation of Voice Activity Detection feature
54
+ - Add `asd` to use our own implementation of Audio Signal Detection feature
55
+ - Add `denoise` to use our own implementation of noise suppression
56
+ - Add `backgroundBlurAmount` to adjust the blur amount when using the background
57
+ blur feature
58
+ - Add `edgeBlurAmount` to adjust the blur amount for edge of the segmented
59
+ person
60
+ - Add `foregroundThreshold` to adjust the threshold to be considered as
61
+ foreground aka the segmented person
62
+ - Add `bgImageUrl` for the image to be used for background replacement
63
+ - Add `videoSegmentation` for specified effects of video segmentation
64
+ - Add `videoSegmentationModel` for specifying segmentation model to be used
65
+ - Add `flipHorizontal` to flip horizontally
66
+
67
+ ```typescript
68
+ export interface InputConstraintSet extends MediaTrackConstraints {
69
+ /**
70
+ * Same purpose as `deviceId` but it gives more information about the device
71
+ * so that we can have extra tolerance on device selection
72
+ */
73
+ device?: DeviceConstraint | ConstraintDeviceParameters;
74
+ /**
75
+ * Whether or not using video segmentation, e.g. background
76
+ * blur/replacement, to specify the effects, intended to be applied to the
77
+ * segment. Available effects are `none`, `blur`, `overlay` or `remove`
78
+ */
79
+ videoSegmentation?: ConstrainDOMString;
80
+ /**
81
+ * Segmentation model to be used for video segmentation, currently only
82
+ * supports `mediapipeSelfie` and `personify`
83
+ */
84
+ videoSegmentationModel?: ConstrainDOMString;
85
+ /**
86
+ * Whether or not using our own noise suppression
87
+ */
88
+ denoise?: ConstrainBoolean;
89
+ /**
90
+ * Voice Activity Detection
91
+ */
92
+ vad?: ConstrainBoolean;
93
+ /**
94
+ * Audio Signal Detection for the purpose of checking if the audio input is
95
+ * hardware muted or unusable
96
+ */
97
+ asd?: ConstrainBoolean;
98
+ /**
99
+ * Flip the video horizontally
100
+ */
101
+ flipHorizontal?: ConstrainBoolean;
102
+ /**
103
+ * Blur size/level parameter when using video segmentation with `blur`
104
+ * effects
105
+ */
106
+ backgroundBlurAmount?: ConstrainULong;
107
+ /**
108
+ * Blur amount applied to the segmented person's edge
109
+ */
110
+ edgeBlurAmount?: ConstrainULong;
111
+ /**
112
+ * Erode level for edge smoothing when using video segmentation
113
+ */
114
+ foregroundThreshold?: ConstrainDouble;
115
+ /**
116
+ * Image Url that is being used for video overlay effects
117
+ */
118
+ bgImageUrl?: ConstrainDOMString;
119
+ }
120
+ ```
121
+
122
+ ### `createMedia`
123
+
124
+ ```typescript
125
+ import {createMedia, createMediaSignals, UserMediaStatus} from '@pexip/media';
126
+ import type {VideoRenderParams} from '@pexip/media';
127
+ import {
128
+ urls as mpUrls,
129
+ createMediapipeSegmenter,
130
+ createPsySegSegmenter,
131
+ createCanvasTransform,
132
+ createVideoTrackProcessor,
133
+ createVideoTrackProcessorWithFallback,
134
+ createVideoProcessor,
135
+ PROCESSING_WIDTH,
136
+ PROCESSING_HEIGHT,
137
+ FOREGROUND_THRESHOLD,
138
+ BACKGROUND_BLUR_AMOUNT,
139
+ EDGE_BLUR_AMOUNT,
140
+ FLIP_HORIZONTAL,
141
+ } from '@pexip/media-processor';
142
+
143
+ // Need some state for the app
144
+ interface State extends VideoRenderParams {
145
+ mute: {
146
+ audio: boolean;
147
+ video: boolean;
148
+ };
149
+ noiseSuppression: boolean;
150
+ vad: boolean;
151
+ asd: boolean;
152
+ updateFrequency: number;
153
+ silentDetectionDuration: number;
154
+ vadThrottleMS: number;
155
+ monitor: boolean;
156
+ channelCount: number;
157
+ }
158
+ export const mediaState: State = {
159
+ mute: {
160
+ audio: false,
161
+ video: false,
162
+ },
163
+ videoSegmentation: 'none',
164
+ noiseSuppression: false,
165
+ vad: false,
166
+ asd: false,
167
+ updateFrequency: 0.5,
168
+ silentDetectionDuration: 4.0,
169
+ vadThrottleMS: 3000,
170
+ width: PROCESSING_WIDTH,
171
+ height: PROCESSING_HEIGHT,
172
+ frameRate: 30,
173
+ bgImageUrl: '',
174
+ monitor: false,
175
+ channelCount: 1,
176
+ foregroundThreshold: FOREGROUND_THRESHOLD,
177
+ backgroundBlurAmount: BACKGROUND_BLUR_AMOUNT,
178
+ edgeBlurAmount: EDGE_BLUR_AMOUNT,
179
+ flipHorizontal: FLIP_HORIZONTAL,
180
+ };
181
+
182
+ // Create required signals with additional `onDevicesChanged`,
183
+ // `onStatusChanged` and `onStreamTrackEnabled` signals
184
+ export const signals = createMediaSignals('demo', [
185
+ 'onDevicesChanged',
186
+ 'onStatusChanged',
187
+ 'onStreamTrackEnabled',
188
+ ]);
189
+
190
+ const audioProcessor = createAudioStreamProcess({
191
+ shouldEnable: () => true,
192
+ denoiseParams: {
193
+ wasmURL: denoiseWasm.href,
194
+ workletModule: mpUrls.denoise.href,
195
+ },
196
+ analyzerUpdateFrequency: mediaState.updateFrequency,
197
+ audioSignalDetectionDuration: mediaState.silentDetectionDuration,
198
+ throttleMs: mediaState.vadThrottleMS,
199
+ onAudioSignalDetected: signals.onSilentDetected.emit,
200
+ onVoiceActivityDetected: signals.onVAD.emit,
201
+ });
202
+
203
+ // Create symbolic link to link bg-blur/selfie_segmentation to a public folder
204
+ // Thus we can create a URL object to get the link to be used for the `gluePath`
205
+ const selfieJs = new URL(
206
+ `./selfie_segmentation/selfie_segmentation.js`,
207
+ document.baseURI,
208
+ );
209
+ const mediapipeSegmenter = createMediapipeSegmenter('selfie_segmentation', {
210
+ modelType: 'general',
211
+ processingWidth: PROCESSING_WIDTH,
212
+ processingHeight: PROCESSING_HEIGHT,
213
+ gluePath: selfieJs.href,
214
+ });
215
+
216
+ const segmenters: Segmenters = {
217
+ mediapipeSelfie: mediapipeSegmenter,
218
+ };
219
+
220
+ const transformer = createCanvasTransform(mediapipeSegmenter, {
221
+ effects: mediaState.videoSegmentation,
222
+ width: mediaState.width,
223
+ height: mediaState.height,
224
+ foregroundThreshold: mediaState.foregroundThreshold,
225
+ backgroundBlurAmount: mediaState.backgroundBlurAmount,
226
+ edgeBlurAmount: mediaState.edgeBlurAmount,
227
+ flipHorizontal: mediaState.flipHorizontal,
228
+ });
229
+ const videoProcessor = createVideoProcessor([transformer]);
230
+
231
+ const videoStreamProcessor = createVideoStreamProcess({
232
+ trackProcessorAPI: 'stream', // Use Stream API when available
233
+ shouldEnable: () => true, // Always Process Video Track
234
+ videoSegmentationModel: 'mediapipeSelfie', // Segmentation Modal
235
+ segmenters,
236
+ transformer,
237
+ videoProcessor,
238
+ processingWidth: mediaState.width,
239
+ processingHeight: mediaState.height,
240
+ onError: error => {
241
+ console.error(error);
242
+ },
243
+ });
244
+
245
+ // Instantiate the media object
246
+ export const mediaController = createMedia({
247
+ getMuteState: () => mediaState.mute,
248
+ signals,
249
+ mediaProcessors: [videoStreamProcessor, audioProcessor],
250
+ });
251
+
252
+ // Hook-up the signals to get the update
253
+ // Subscribe the onMediaChanged signal to get the latest Media object change event
254
+ signals.onMediaChanged.add(media => setLocalMedia(media)); // Assume there is a local function `setLocalMedia`
255
+ // Subscribe the onStatusChanged signal to get the latest Media status change event
256
+ signals.onStatusChanged.add(media => setMediaStatus(media)); // Assume there is a local function `setMediaStatus`
257
+ // Subscribe onStreamTrackEnabled signal to get the MediaStreamTrack['enabled'] change event
258
+ signals.onStreamTrackEnabled.add(track => {
259
+ console.log(track);
260
+ });
261
+
262
+ // Later we can initial a gUM to get a MediaStream
263
+ mediaController.getUserMedia({
264
+ audio: {
265
+ sampleRate: 48000, // Ideal sample rate for our own noise suppression implementation
266
+ denoise: true, // Use our own implementation of noise suppression
267
+ noiseSuppression: false, // Disable the built-in noise suppression
268
+ vad: true, // Use Voice Activity Detection
269
+ asd: true, // Use Audio Signal Detection to check if the microphone is malfunctioned
270
+ },
271
+ video: {
272
+ videoSegmentation: 'blur', // Use background blur
273
+ blurLevel: 21,
274
+ },
275
+ });
276
+
277
+ // Access the current `MediaStream`
278
+ mediaController.media.stream;
279
+ // Get audio mute state
280
+ mediaController.media.audioMuted;
281
+ // Mute audio
282
+ mediaController.media.muteAudio(true);
283
+ // Get video mute state
284
+ mediaController.media.videoMuted;
285
+ // Mute video
286
+ mediaController.media.muteVideo(true);
287
+ // Get the status
288
+ mediaController.media.status;
289
+ // Update the status
290
+ mediaController.media.status = UserMediaStatus.Initial;
291
+ // Stop the `MediaStream`
292
+ await mediaController.media.release();
293
+
294
+ // Later we can make changes to the media on-demand without initiate a new gUM call
295
+
296
+ // Turn off background blur
297
+ await mediaController.media.applyConstraints({
298
+ video: {videoSegmentation: 'none'},
299
+ });
300
+ // Turn on background blur
301
+ await mediaController.media.applyConstraints({
302
+ video: {videoSegmentation: 'blur'},
303
+ });
304
+ // Use our own noise suppression
305
+ await mediaController.media.applyConstraints({
306
+ audio: {denoise: true, noiseSuppression: false},
307
+ });
308
+ // Use build-in noise suppression
309
+ await mediaController.media.applyConstraints({
310
+ audio: {denoise: false, noiseSuppression: true},
311
+ });
312
+ ```
313
+
314
+ ### `createPreviewController`
315
+
316
+ ```typescript
317
+ const {createPreviewController} = require('@pexip/media');
318
+
319
+ // Some states from the App
320
+ interface AppState {
321
+ media: Media;
322
+ devices: MediaDeviceInfo[];
323
+ }
324
+ // Some functions from the App
325
+ const updateStream = (constraints: MediaDeviceRequest) => Promise<void>;
326
+
327
+ const onMediaChangedSignal = createSignal<Media>();
328
+
329
+ // Instantiate the controller
330
+ const controller = createPreviewController({
331
+ getDesiredResolution: () => ({}),
332
+ getCurrentDevices: () => state.devices,
333
+ getCurrentMedia: () => state.media,
334
+ updateMainStream: updateStream,
335
+ mediaSignal: onMediaChangedSignal,
336
+ getSegmentationOptions: () => ({
337
+ effects: mediaState.videoSegmentation,
338
+ erode: mediaState.erode,
339
+ blurLevel: mediaState.blurLevel,
340
+ }),
341
+ videoProcessingEnabled: true,
342
+ updateMainStream: mc.getUserMediaAsync,
343
+ onEnded: () => {
344
+ close();
345
+ },
346
+ psySegScriptLoaded: true,
347
+ });
348
+
349
+ // Want to learn more? Please checkout the `@pexip/media-demo` sample app to try
350
+ ```