@blockcast/moq-media-sync 0.0.0-stage → 0.1.0-blockcast.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-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Luke Curley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @moq/media-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Transport-neutral media clock, pacing, cancellation, and generation-safe delivery queues shared by Hang and moqtail.
4
+
5
+ Delivery callbacks stage effects and return a commit function. Resetting or cancelling the owning track after an await prevents that commit from running.
6
+
7
+ ## Release
8
+
9
+ `@moq/media-sync` is proposed upstream to [moq-dev/moq](https://github.com/moq-dev/moq) from
10
+ [Blockcast/moq `feat/media-sync-core`](https://github.com/Blockcast/moq/tree/feat/media-sync-core) and is not
11
+ released there yet. The `@moq` scope belongs to moq-dev, so this workspace package is private and is never
12
+ published under that name.
13
+
14
+ Consumers outside this repository install the temporary Blockcast release through an npm alias, which keeps
15
+ their `@moq/media-sync` imports unchanged:
16
+
17
+ ```json
18
+ "@moq/media-sync": "npm:@blockcast/moq-media-sync@0.1.0-blockcast.1"
19
+ ```
20
+
21
+ `bun run pack:blockcast` builds that tarball with the identity and upstream provenance in `release.json`, records
22
+ the source commit in the manifest's `blockcast.source`, refuses `file:`/`link:`/`workspace:`/absolute dependency
23
+ specs, installs it into a temporary consumer, imports both entrypoints, runs the shared clock vectors, and removes
24
+ the temporary files.
25
+
26
+ Switch back once moq-dev publishes `@moq/media-sync` with these exports: point the alias at the upstream package,
27
+ confirm the shared vectors pass against it, and delete `release.json` and `pack.ts`.
package/index.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ export type MediaKind = "video" | "audio";
2
+ export type MediaDelivery = {
3
+ commit(): void;
4
+ discard?(): void;
5
+ };
6
+ export type MediaDeliveryStage = (signal: AbortSignal) => null | (() => void) | MediaDelivery | Promise<null | (() => void) | MediaDelivery>;
7
+ export interface MediaSyncOptions {
8
+ now?: () => number;
9
+ buffer?: number | Partial<Record<MediaKind, number>>;
10
+ /** Number of media timestamp units in one clock/buffer unit. */
11
+ timestampScale?: number;
12
+ onState?: (reference: number | undefined, timestamp: number | undefined) => void;
13
+ }
14
+ /** Transport-neutral media clock and generation-safe per-track delivery queue. */
15
+ export declare class MediaSync {
16
+ #private;
17
+ constructor(options?: MediaSyncOptions);
18
+ get reference(): number | undefined;
19
+ get timestamp(): number | undefined;
20
+ buffer(kind: MediaKind): number;
21
+ setBuffer(buffer: number, kind?: MediaKind): void;
22
+ received(timestamp: number): void;
23
+ now(kind?: MediaKind): number | undefined;
24
+ wait(timestamp: number, kind?: MediaKind, signal?: AbortSignal): Promise<void>;
25
+ captureSignal(kind: MediaKind): AbortSignal;
26
+ enqueue(timestamp: number, kind: MediaKind, stage: MediaDeliveryStage, onError?: (error: unknown) => void, capturedSignal?: AbortSignal, pace?: boolean, serialize?: boolean): void;
27
+ /** Start an unpaced stage immediately while retaining generation ownership. */
28
+ deliver(kind: MediaKind, stage: MediaDeliveryStage, onError?: (error: unknown) => void, capturedSignal?: AbortSignal): void;
29
+ drain(kind: MediaKind): Promise<void>;
30
+ cancel(kind: MediaKind): void;
31
+ reset(): void;
32
+ }
33
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;AAE1C,MAAM,MAAM,aAAa,GAAG;IAC3B,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,CAAC,IAAI,IAAI,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,CAChC,MAAM,EAAE,WAAW,KACf,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,aAAa,GAAG,OAAO,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,aAAa,CAAC,CAAC;AAExF,MAAM,WAAW,gBAAgB;IAChC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IACrD,gEAAgE;IAChE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;CACjF;AAUD,kFAAkF;AAClF,qBAAa,SAAS;;gBAeT,OAAO,GAAE,gBAAqB;IAc1C,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,MAAM,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM;IAI/B,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,SAAS,GAAG,IAAI;IAYjD,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAQjC,GAAG,CAAC,IAAI,GAAE,SAAmB,GAAG,MAAM,GAAG,SAAS;IAK5C,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,GAAE,SAAmB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IA2B7F,aAAa,CAAC,IAAI,EAAE,SAAS,GAAG,WAAW;IAI3C,OAAO,CACN,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,kBAAkB,EACzB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,EAClC,cAAc,CAAC,EAAE,WAAW,EAC5B,IAAI,UAAO,EACX,SAAS,UAAO,GACd,IAAI;IA2BP,+EAA+E;IAC/E,OAAO,CACN,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,kBAAkB,EACzB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,EAClC,cAAc,CAAC,EAAE,WAAW,GAC1B,IAAI;IAsBD,KAAK,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3C,MAAM,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI;IAO7B,KAAK,IAAI,IAAI;CAiBb"}
package/index.js ADDED
@@ -0,0 +1,193 @@
1
+ function deferred() {
2
+ let resolve;
3
+ const promise = new Promise((done) => {
4
+ resolve = done;
5
+ });
6
+ return { promise, resolve };
7
+ }
8
+ /** Transport-neutral media clock and generation-safe per-track delivery queue. */
9
+ export class MediaSync {
10
+ #now;
11
+ #buffers;
12
+ #timestampScale;
13
+ #reference;
14
+ #timestamp;
15
+ #onState;
16
+ #update = deferred();
17
+ #tails = { video: Promise.resolve(), audio: Promise.resolve() };
18
+ #independent = { video: new Set(), audio: new Set() };
19
+ #controllers = {
20
+ video: new AbortController(),
21
+ audio: new AbortController(),
22
+ };
23
+ constructor(options = {}) {
24
+ this.#now = options.now ?? (() => performance.now());
25
+ const buffer = options.buffer ?? 0;
26
+ this.#buffers =
27
+ typeof buffer === "number"
28
+ ? { video: buffer, audio: buffer }
29
+ : { video: buffer.video ?? 0, audio: buffer.audio ?? 0 };
30
+ this.#timestampScale = options.timestampScale ?? 1;
31
+ if (!Number.isFinite(this.#timestampScale) || this.#timestampScale <= 0) {
32
+ throw new Error("timestampScale must be finite and greater than zero");
33
+ }
34
+ this.#onState = options.onState;
35
+ }
36
+ get reference() {
37
+ return this.#reference;
38
+ }
39
+ get timestamp() {
40
+ return this.#timestamp;
41
+ }
42
+ buffer(kind) {
43
+ return this.#buffers[kind];
44
+ }
45
+ setBuffer(buffer, kind) {
46
+ if (kind) {
47
+ if (buffer === this.#buffers[kind])
48
+ return;
49
+ this.#buffers[kind] = buffer;
50
+ }
51
+ else {
52
+ if (buffer === this.#buffers.video && buffer === this.#buffers.audio)
53
+ return;
54
+ this.#buffers.video = buffer;
55
+ this.#buffers.audio = buffer;
56
+ }
57
+ this.#wake();
58
+ }
59
+ received(timestamp) {
60
+ if (this.#timestamp === undefined || timestamp > this.#timestamp)
61
+ this.#timestamp = timestamp;
62
+ const reference = this.#now() - timestamp / this.#timestampScale;
63
+ if (this.#reference === undefined || reference < this.#reference)
64
+ this.#reference = reference;
65
+ this.#onState?.(this.#reference, this.#timestamp);
66
+ this.#wake();
67
+ }
68
+ now(kind = "video") {
69
+ if (this.#reference === undefined)
70
+ return undefined;
71
+ return (this.#now() - this.#reference - this.#buffers[kind]) * this.#timestampScale;
72
+ }
73
+ async wait(timestamp, kind = "video", signal) {
74
+ if (signal?.aborted)
75
+ return;
76
+ if (this.#reference === undefined)
77
+ throw new Error("reference not set; call received() first");
78
+ for (;;) {
79
+ const reference = this.#reference;
80
+ if (reference === undefined || signal?.aborted)
81
+ return;
82
+ const sleep = reference - (this.#now() - timestamp / this.#timestampScale) + this.#buffers[kind];
83
+ if (sleep < 5)
84
+ return;
85
+ await new Promise((resolve) => {
86
+ let done = false;
87
+ const finish = () => {
88
+ if (done)
89
+ return;
90
+ done = true;
91
+ clearTimeout(timeout);
92
+ signal?.removeEventListener("abort", finish);
93
+ resolve();
94
+ };
95
+ const timeout = setTimeout(finish, sleep);
96
+ signal?.addEventListener("abort", finish, { once: true });
97
+ void this.#update.promise.then(finish);
98
+ if (signal?.aborted)
99
+ finish();
100
+ });
101
+ }
102
+ }
103
+ captureSignal(kind) {
104
+ return this.#controllers[kind].signal;
105
+ }
106
+ enqueue(timestamp, kind, stage, onError, capturedSignal, pace = true, serialize = true) {
107
+ const signal = capturedSignal ?? this.captureSignal(kind);
108
+ if (!this.#accepts(kind, signal))
109
+ return;
110
+ const run = async () => {
111
+ if (!this.#accepts(kind, signal))
112
+ return;
113
+ if (pace)
114
+ await this.wait(timestamp, kind, signal);
115
+ if (!this.#accepts(kind, signal))
116
+ return;
117
+ const staged = await stage(signal);
118
+ if (!staged)
119
+ return;
120
+ const delivery = typeof staged === "function" ? { commit: staged } : staged;
121
+ if (this.#accepts(kind, signal))
122
+ delivery.commit();
123
+ else
124
+ delivery.discard?.();
125
+ };
126
+ const execute = () => run().catch((error) => {
127
+ if (!signal.aborted)
128
+ onError?.(error);
129
+ });
130
+ if (!serialize) {
131
+ const independent = this.#independent[kind];
132
+ const pending = execute().finally(() => independent.delete(pending));
133
+ independent.add(pending);
134
+ return;
135
+ }
136
+ const independent = [...this.#independent[kind]];
137
+ this.#tails[kind] = Promise.all([this.#tails[kind].catch(() => undefined), ...independent]).then(execute);
138
+ }
139
+ /** Start an unpaced stage immediately while retaining generation ownership. */
140
+ deliver(kind, stage, onError, capturedSignal) {
141
+ const signal = capturedSignal ?? this.captureSignal(kind);
142
+ if (!this.#accepts(kind, signal))
143
+ return;
144
+ let staged;
145
+ try {
146
+ staged = stage(signal);
147
+ }
148
+ catch (error) {
149
+ onError?.(error);
150
+ return;
151
+ }
152
+ void Promise.resolve(staged)
153
+ .then((staged) => {
154
+ if (!staged)
155
+ return;
156
+ const delivery = typeof staged === "function" ? { commit: staged } : staged;
157
+ if (this.#accepts(kind, signal))
158
+ delivery.commit();
159
+ else
160
+ delivery.discard?.();
161
+ })
162
+ .catch((error) => {
163
+ if (!signal.aborted)
164
+ onError?.(error);
165
+ });
166
+ }
167
+ async drain(kind) {
168
+ await this.#tails[kind];
169
+ await Promise.all(this.#independent[kind]);
170
+ }
171
+ cancel(kind) {
172
+ this.#controllers[kind].abort();
173
+ this.#controllers[kind] = new AbortController();
174
+ this.#tails[kind] = Promise.resolve();
175
+ this.#independent[kind] = new Set();
176
+ }
177
+ reset() {
178
+ this.cancel("video");
179
+ this.cancel("audio");
180
+ this.#reference = undefined;
181
+ this.#timestamp = undefined;
182
+ this.#onState?.(undefined, undefined);
183
+ this.#wake();
184
+ }
185
+ #accepts(kind, signal) {
186
+ return !signal.aborted && signal === this.#controllers[kind].signal;
187
+ }
188
+ #wake() {
189
+ this.#update.resolve();
190
+ this.#update = deferred();
191
+ }
192
+ }
193
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAmBA,SAAS,QAAQ;IAChB,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,kFA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AG,EAAE,CAAC;IACrC,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,QAAQ,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,KAAK,EAAE,CAAC;IACd,CAAC;IAED,QAAQ,CAAC,IAAe,EAAE,MAAmB;QAC5C,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,KAAK,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC;IACrE,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,QAAQ,EAAE,CAAC;IAC3B,CAAC;CACD","sourcesContent":["export type MediaKind = \"video\" | \"audio\";\n\nexport type MediaDelivery = {\n\tcommit(): void;\n\tdiscard?(): void;\n};\n\nexport type MediaDeliveryStage = (\n\tsignal: AbortSignal,\n) => null | (() => void) | MediaDelivery | Promise<null | (() => void) | MediaDelivery>;\n\nexport interface MediaSyncOptions {\n\tnow?: () => number;\n\tbuffer?: number | Partial<Record<MediaKind, number>>;\n\t/** Number of media timestamp units in one clock/buffer unit. */\n\ttimestampScale?: number;\n\tonState?: (reference: number | undefined, timestamp: number | undefined) => void;\n}\n\nfunction deferred() {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\n/** Transport-neutral media clock and generation-safe per-track delivery queue. */\nexport class MediaSync {\n\t#now: () => number;\n\t#buffers: Record<MediaKind, number>;\n\t#timestampScale: number;\n\t#reference: number | undefined;\n\t#timestamp: number | undefined;\n\t#onState?: MediaSyncOptions[\"onState\"];\n\t#update = deferred();\n\t#tails: Record<MediaKind, Promise<void>> = { video: Promise.resolve(), audio: Promise.resolve() };\n\t#independent: Record<MediaKind, Set<Promise<void>>> = { video: new Set(), audio: new Set() };\n\t#controllers: Record<MediaKind, AbortController> = {\n\t\tvideo: new AbortController(),\n\t\taudio: new AbortController(),\n\t};\n\n\tconstructor(options: MediaSyncOptions = {}) {\n\t\tthis.#now = options.now ?? (() => performance.now());\n\t\tconst buffer = options.buffer ?? 0;\n\t\tthis.#buffers =\n\t\t\ttypeof buffer === \"number\"\n\t\t\t\t? { video: buffer, audio: buffer }\n\t\t\t\t: { video: buffer.video ?? 0, audio: buffer.audio ?? 0 };\n\t\tthis.#timestampScale = options.timestampScale ?? 1;\n\t\tif (!Number.isFinite(this.#timestampScale) || this.#timestampScale <= 0) {\n\t\t\tthrow new Error(\"timestampScale must be finite and greater than zero\");\n\t\t}\n\t\tthis.#onState = options.onState;\n\t}\n\n\tget reference(): number | undefined {\n\t\treturn this.#reference;\n\t}\n\n\tget timestamp(): number | undefined {\n\t\treturn this.#timestamp;\n\t}\n\n\tbuffer(kind: MediaKind): number {\n\t\treturn this.#buffers[kind];\n\t}\n\n\tsetBuffer(buffer: number, kind?: MediaKind): void {\n\t\tif (kind) {\n\t\t\tif (buffer === this.#buffers[kind]) return;\n\t\t\tthis.#buffers[kind] = buffer;\n\t\t} else {\n\t\t\tif (buffer === this.#buffers.video && buffer === this.#buffers.audio) return;\n\t\t\tthis.#buffers.video = buffer;\n\t\t\tthis.#buffers.audio = buffer;\n\t\t}\n\t\tthis.#wake();\n\t}\n\n\treceived(timestamp: number): void {\n\t\tif (this.#timestamp === undefined || timestamp > this.#timestamp) this.#timestamp = timestamp;\n\t\tconst reference = this.#now() - timestamp / this.#timestampScale;\n\t\tif (this.#reference === undefined || reference < this.#reference) this.#reference = reference;\n\t\tthis.#onState?.(this.#reference, this.#timestamp);\n\t\tthis.#wake();\n\t}\n\n\tnow(kind: MediaKind = \"video\"): number | undefined {\n\t\tif (this.#reference === undefined) return undefined;\n\t\treturn (this.#now() - this.#reference - this.#buffers[kind]) * this.#timestampScale;\n\t}\n\n\tasync wait(timestamp: number, kind: MediaKind = \"video\", signal?: AbortSignal): Promise<void> {\n\t\tif (signal?.aborted) return;\n\t\tif (this.#reference === undefined) throw new Error(\"reference not set; call received() first\");\n\n\t\tfor (;;) {\n\t\t\tconst reference = this.#reference;\n\t\t\tif (reference === undefined || signal?.aborted) return;\n\t\t\tconst sleep = reference - (this.#now() - timestamp / this.#timestampScale) + this.#buffers[kind];\n\t\t\tif (sleep < 5) return;\n\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tlet done = false;\n\t\t\t\tconst finish = () => {\n\t\t\t\t\tif (done) return;\n\t\t\t\t\tdone = true;\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", finish);\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tconst timeout = setTimeout(finish, sleep);\n\t\t\t\tsignal?.addEventListener(\"abort\", finish, { once: true });\n\t\t\t\tvoid this.#update.promise.then(finish);\n\t\t\t\tif (signal?.aborted) finish();\n\t\t\t});\n\t\t}\n\t}\n\n\tcaptureSignal(kind: MediaKind): AbortSignal {\n\t\treturn this.#controllers[kind].signal;\n\t}\n\n\tenqueue(\n\t\ttimestamp: number,\n\t\tkind: MediaKind,\n\t\tstage: MediaDeliveryStage,\n\t\tonError?: (error: unknown) => void,\n\t\tcapturedSignal?: AbortSignal,\n\t\tpace = true,\n\t\tserialize = true,\n\t): void {\n\t\tconst signal = capturedSignal ?? this.captureSignal(kind);\n\t\tif (!this.#accepts(kind, signal)) return;\n\t\tconst run = async () => {\n\t\t\tif (!this.#accepts(kind, signal)) return;\n\t\t\tif (pace) await this.wait(timestamp, kind, signal);\n\t\t\tif (!this.#accepts(kind, signal)) return;\n\t\t\tconst staged = await stage(signal);\n\t\t\tif (!staged) return;\n\t\t\tconst delivery = typeof staged === \"function\" ? { commit: staged } : staged;\n\t\t\tif (this.#accepts(kind, signal)) delivery.commit();\n\t\t\telse delivery.discard?.();\n\t\t};\n\t\tconst execute = () =>\n\t\t\trun().catch((error) => {\n\t\t\t\tif (!signal.aborted) onError?.(error);\n\t\t\t});\n\t\tif (!serialize) {\n\t\t\tconst independent = this.#independent[kind];\n\t\t\tconst pending = execute().finally(() => independent.delete(pending));\n\t\t\tindependent.add(pending);\n\t\t\treturn;\n\t\t}\n\t\tconst independent = [...this.#independent[kind]];\n\t\tthis.#tails[kind] = Promise.all([this.#tails[kind].catch(() => undefined), ...independent]).then(execute);\n\t}\n\n\t/** Start an unpaced stage immediately while retaining generation ownership. */\n\tdeliver(\n\t\tkind: MediaKind,\n\t\tstage: MediaDeliveryStage,\n\t\tonError?: (error: unknown) => void,\n\t\tcapturedSignal?: AbortSignal,\n\t): void {\n\t\tconst signal = capturedSignal ?? this.captureSignal(kind);\n\t\tif (!this.#accepts(kind, signal)) return;\n\t\tlet staged: ReturnType<MediaDeliveryStage>;\n\t\ttry {\n\t\t\tstaged = stage(signal);\n\t\t} catch (error) {\n\t\t\tonError?.(error);\n\t\t\treturn;\n\t\t}\n\t\tvoid Promise.resolve(staged)\n\t\t\t.then((staged) => {\n\t\t\t\tif (!staged) return;\n\t\t\t\tconst delivery = typeof staged === \"function\" ? { commit: staged } : staged;\n\t\t\t\tif (this.#accepts(kind, signal)) delivery.commit();\n\t\t\t\telse delivery.discard?.();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (!signal.aborted) onError?.(error);\n\t\t\t});\n\t}\n\n\tasync drain(kind: MediaKind): Promise<void> {\n\t\tawait this.#tails[kind];\n\t\tawait Promise.all(this.#independent[kind]);\n\t}\n\n\tcancel(kind: MediaKind): void {\n\t\tthis.#controllers[kind].abort();\n\t\tthis.#controllers[kind] = new AbortController();\n\t\tthis.#tails[kind] = Promise.resolve();\n\t\tthis.#independent[kind] = new Set();\n\t}\n\n\treset(): void {\n\t\tthis.cancel(\"video\");\n\t\tthis.cancel(\"audio\");\n\t\tthis.#reference = undefined;\n\t\tthis.#timestamp = undefined;\n\t\tthis.#onState?.(undefined, undefined);\n\t\tthis.#wake();\n\t}\n\n\t#accepts(kind: MediaKind, signal: AbortSignal): boolean {\n\t\treturn !signal.aborted && signal === this.#controllers[kind].signal;\n\t}\n\n\t#wake(): void {\n\t\tthis.#update.resolve();\n\t\tthis.#update = deferred();\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
- "name": "@blockcast/moq-media-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@blockcast/moq-media-sync",
3
+ "type": "module",
4
+ "version": "0.1.0-blockcast.1",
5
+ "description": "Transport-neutral media clock and generation-safe delivery queue",
6
+ "license": "(MIT OR Apache-2.0)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Blockcast/hang-mmt-fec.git",
10
+ "directory": "js/media-sync"
11
+ },
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./index.d.ts",
16
+ "default": "./index.js"
17
+ },
18
+ "./vectors": {
19
+ "types": "./vectors.d.ts",
20
+ "default": "./vectors.js"
21
+ }
22
+ },
23
+ "blockcast": {
24
+ "source": "Blockcast/hang-mmt-fec@f7f4b603a21eb16645fef31d8d233e50815828e5",
25
+ "upstream": {
26
+ "package": "@moq/media-sync",
27
+ "repository": "https://github.com/moq-dev/moq",
28
+ "base": "6a3459cad8a6002b84e669827699638717744537",
29
+ "proposal": "https://github.com/Blockcast/moq/tree/feat/media-sync-core",
30
+ "proposalCommit": "a4f8a552f952c683b72cf1a6365bf5a476910e60"
31
+ },
32
+ "switchBack": "Depend on @moq/media-sync from npm and drop this package once moq-dev publishes it with these exports and the shared vectors still pass."
33
+ }
34
+ }
package/vectors.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ export declare const MEDIA_SYNC_CLOCK_VECTORS: readonly [{
2
+ readonly name: "millisecond clock";
3
+ readonly timestampScale: 1;
4
+ readonly anchorClock: 1000;
5
+ readonly anchorTimestamp: 900;
6
+ readonly readClock: 1030;
7
+ readonly buffer: {
8
+ readonly video: 20;
9
+ readonly audio: 40;
10
+ };
11
+ readonly expected: {
12
+ readonly reference: 100;
13
+ readonly timestamp: 900;
14
+ readonly videoNow: 910;
15
+ readonly audioNow: 890;
16
+ };
17
+ }, {
18
+ readonly name: "microsecond media timestamps";
19
+ readonly timestampScale: 1000;
20
+ readonly anchorClock: 1000;
21
+ readonly anchorTimestamp: 900000;
22
+ readonly readClock: 1030;
23
+ readonly buffer: {
24
+ readonly video: 20;
25
+ readonly audio: 40;
26
+ };
27
+ readonly expected: {
28
+ readonly reference: 100;
29
+ readonly timestamp: 900000;
30
+ readonly videoNow: 910000;
31
+ readonly audioNow: 890000;
32
+ };
33
+ }];
34
+ export declare const MEDIA_SYNC_PACING_VECTORS: readonly [{
35
+ readonly name: "paced video delivery";
36
+ readonly kind: "video";
37
+ readonly anchorClockMs: 1000;
38
+ readonly anchorTimestampMs: 900;
39
+ readonly deliveryTimestampMs: 1000;
40
+ readonly earlyClockMs: 1030;
41
+ readonly dueClockMs: 1051;
42
+ readonly bufferMs: 20;
43
+ }, {
44
+ readonly name: "paced audio delivery";
45
+ readonly kind: "audio";
46
+ readonly anchorClockMs: 2000;
47
+ readonly anchorTimestampMs: 1900;
48
+ readonly deliveryTimestampMs: 2000;
49
+ readonly earlyClockMs: 2030;
50
+ readonly dueClockMs: 2051;
51
+ readonly bufferMs: 20;
52
+ }];
53
+ export declare const MEDIA_SYNC_DELIVERY_VECTORS: readonly [{
54
+ readonly name: "audio cancellation retirement";
55
+ readonly kind: "audio";
56
+ readonly retire: "cancel";
57
+ readonly firstTimestampMs: 7;
58
+ readonly queuedTimestampMs: 8;
59
+ readonly reusedTimestampMs: 7;
60
+ }, {
61
+ readonly name: "audio reset retirement";
62
+ readonly kind: "audio";
63
+ readonly retire: "reset";
64
+ readonly firstTimestampMs: 17;
65
+ readonly queuedTimestampMs: 18;
66
+ readonly reusedTimestampMs: 17;
67
+ }, {
68
+ readonly name: "video cancellation retirement";
69
+ readonly kind: "video";
70
+ readonly retire: "cancel";
71
+ readonly firstTimestampMs: 27;
72
+ readonly queuedTimestampMs: 28;
73
+ readonly reusedTimestampMs: 27;
74
+ }, {
75
+ readonly name: "video reset retirement";
76
+ readonly kind: "video";
77
+ readonly retire: "reset";
78
+ readonly firstTimestampMs: 37;
79
+ readonly queuedTimestampMs: 38;
80
+ readonly reusedTimestampMs: 37;
81
+ }];
82
+ //# sourceMappingURL=vectors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vectors.d.ts","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmB3B,CAAC;AAEX,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;EAqB5B,CAAC;AAEX,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiC9B,CAAC"}
package/vectors.js ADDED
@@ -0,0 +1,77 @@
1
+ export const MEDIA_SYNC_CLOCK_VECTORS = [
2
+ {
3
+ name: "millisecond clock",
4
+ timestampScale: 1,
5
+ anchorClock: 1_000,
6
+ anchorTimestamp: 900,
7
+ readClock: 1_030,
8
+ buffer: { video: 20, audio: 40 },
9
+ expected: { reference: 100, timestamp: 900, videoNow: 910, audioNow: 890 },
10
+ },
11
+ {
12
+ name: "microsecond media timestamps",
13
+ timestampScale: 1_000,
14
+ anchorClock: 1_000,
15
+ anchorTimestamp: 900_000,
16
+ readClock: 1_030,
17
+ buffer: { video: 20, audio: 40 },
18
+ expected: { reference: 100, timestamp: 900_000, videoNow: 910_000, audioNow: 890_000 },
19
+ },
20
+ ];
21
+ export const MEDIA_SYNC_PACING_VECTORS = [
22
+ {
23
+ name: "paced video delivery",
24
+ kind: "video",
25
+ anchorClockMs: 1_000,
26
+ anchorTimestampMs: 900,
27
+ deliveryTimestampMs: 1_000,
28
+ earlyClockMs: 1_030,
29
+ dueClockMs: 1_051,
30
+ bufferMs: 20,
31
+ },
32
+ {
33
+ name: "paced audio delivery",
34
+ kind: "audio",
35
+ anchorClockMs: 2_000,
36
+ anchorTimestampMs: 1_900,
37
+ deliveryTimestampMs: 2_000,
38
+ earlyClockMs: 2_030,
39
+ dueClockMs: 2_051,
40
+ bufferMs: 20,
41
+ },
42
+ ];
43
+ export const MEDIA_SYNC_DELIVERY_VECTORS = [
44
+ {
45
+ name: "audio cancellation retirement",
46
+ kind: "audio",
47
+ retire: "cancel",
48
+ firstTimestampMs: 7,
49
+ queuedTimestampMs: 8,
50
+ reusedTimestampMs: 7,
51
+ },
52
+ {
53
+ name: "audio reset retirement",
54
+ kind: "audio",
55
+ retire: "reset",
56
+ firstTimestampMs: 17,
57
+ queuedTimestampMs: 18,
58
+ reusedTimestampMs: 17,
59
+ },
60
+ {
61
+ name: "video cancellation retirement",
62
+ kind: "video",
63
+ retire: "cancel",
64
+ firstTimestampMs: 27,
65
+ queuedTimestampMs: 28,
66
+ reusedTimestampMs: 27,
67
+ },
68
+ {
69
+ name: "video reset retirement",
70
+ kind: "video",
71
+ retire: "reset",
72
+ firstTimestampMs: 37,
73
+ queuedTimestampMs: 38,
74
+ reusedTimestampMs: 37,
75
+ },
76
+ ];
77
+ //# sourceMappingURL=vectors.js.map
package/vectors.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vectors.js","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC;QACC,IAAI,EAAE,mBAAmB;QACzB,cAAc,EAAE,CAAC;QACjB,WAAW,EAAE,KAAK;QAClB,eAAe,EAAE,GAAG;QACpB,SAAS,EAAE,KAAK;QAChB,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE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ACf,gBAAgB,EAAE,EAAE;QACpB,iBAAiB,EAAE,EAAE;QACrB,iBAAiB,EAAE,EAAE;KACrB;IACD;QACC,IAAI,EAAE,+BAA+B;QACrC,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,QAAQ;QAChB,gBAAgB,EAAE,EAAE;QACpB,iBAAiB,EAAE,EAAE;QACrB,iBAAiB,EAAE,EAAE;KACrB;IACD;QACC,IAAI,EAAE,wBAAwB;QAC9B,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,OAAO;QACf,gBAAgB,EAAE,EAAE;QACpB,iBAAiB,EAAE,EAAE;QACrB,iBAAiB,EAAE,EAAE;KACrB;CACQ,CAAC","sourcesContent":["export const MEDIA_SYNC_CLOCK_VECTORS = [\n\t{\n\t\tname: \"millisecond clock\",\n\t\ttimestampScale: 1,\n\t\tanchorClock: 1_000,\n\t\tanchorTimestamp: 900,\n\t\treadClock: 1_030,\n\t\tbuffer: { video: 20, audio: 40 },\n\t\texpected: { reference: 100, timestamp: 900, videoNow: 910, audioNow: 890 },\n\t},\n\t{\n\t\tname: \"microsecond media timestamps\",\n\t\ttimestampScale: 1_000,\n\t\tanchorClock: 1_000,\n\t\tanchorTimestamp: 900_000,\n\t\treadClock: 1_030,\n\t\tbuffer: { video: 20, audio: 40 },\n\t\texpected: { reference: 100, timestamp: 900_000, videoNow: 910_000, audioNow: 890_000 },\n\t},\n] as const;\n\nexport const MEDIA_SYNC_PACING_VECTORS = [\n\t{\n\t\tname: \"paced video delivery\",\n\t\tkind: \"video\",\n\t\tanchorClockMs: 1_000,\n\t\tanchorTimestampMs: 900,\n\t\tdeliveryTimestampMs: 1_000,\n\t\tearlyClockMs: 1_030,\n\t\tdueClockMs: 1_051,\n\t\tbufferMs: 20,\n\t},\n\t{\n\t\tname: \"paced audio delivery\",\n\t\tkind: \"audio\",\n\t\tanchorClockMs: 2_000,\n\t\tanchorTimestampMs: 1_900,\n\t\tdeliveryTimestampMs: 2_000,\n\t\tearlyClockMs: 2_030,\n\t\tdueClockMs: 2_051,\n\t\tbufferMs: 20,\n\t},\n] as const;\n\nexport const MEDIA_SYNC_DELIVERY_VECTORS = [\n\t{\n\t\tname: \"audio cancellation retirement\",\n\t\tkind: \"audio\",\n\t\tretire: \"cancel\",\n\t\tfirstTimestampMs: 7,\n\t\tqueuedTimestampMs: 8,\n\t\treusedTimestampMs: 7,\n\t},\n\t{\n\t\tname: \"audio reset retirement\",\n\t\tkind: \"audio\",\n\t\tretire: \"reset\",\n\t\tfirstTimestampMs: 17,\n\t\tqueuedTimestampMs: 18,\n\t\treusedTimestampMs: 17,\n\t},\n\t{\n\t\tname: \"video cancellation retirement\",\n\t\tkind: \"video\",\n\t\tretire: \"cancel\",\n\t\tfirstTimestampMs: 27,\n\t\tqueuedTimestampMs: 28,\n\t\treusedTimestampMs: 27,\n\t},\n\t{\n\t\tname: \"video reset retirement\",\n\t\tkind: \"video\",\n\t\tretire: \"reset\",\n\t\tfirstTimestampMs: 37,\n\t\tqueuedTimestampMs: 38,\n\t\treusedTimestampMs: 37,\n\t},\n] as const;\n"]}