@caprid/moq-core 0.0.0 → 0.1.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.
Files changed (57) hide show
  1. package/LICENSE +20 -0
  2. package/NOTICE +5 -0
  3. package/README.md +37 -2
  4. package/UPSTREAM.json +38 -0
  5. package/dist/index.d.ts +18 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +10 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/protocol/bytes.d.ts +59 -0
  10. package/dist/protocol/bytes.d.ts.map +1 -0
  11. package/dist/protocol/bytes.js +211 -0
  12. package/dist/protocol/bytes.js.map +1 -0
  13. package/dist/protocol/control-messages.d.ts +560 -0
  14. package/dist/protocol/control-messages.d.ts.map +1 -0
  15. package/dist/protocol/control-messages.js +1146 -0
  16. package/dist/protocol/control-messages.js.map +1 -0
  17. package/dist/protocol/errors.d.ts +64 -0
  18. package/dist/protocol/errors.d.ts.map +1 -0
  19. package/dist/protocol/errors.js +67 -0
  20. package/dist/protocol/errors.js.map +1 -0
  21. package/dist/protocol/object-stream.d.ts +133 -0
  22. package/dist/protocol/object-stream.d.ts.map +1 -0
  23. package/dist/protocol/object-stream.js +265 -0
  24. package/dist/protocol/object-stream.js.map +1 -0
  25. package/dist/protocol/publish-session.d.ts +196 -0
  26. package/dist/protocol/publish-session.d.ts.map +1 -0
  27. package/dist/protocol/publish-session.js +1174 -0
  28. package/dist/protocol/publish-session.js.map +1 -0
  29. package/dist/protocol/request-stream.d.ts +51 -0
  30. package/dist/protocol/request-stream.d.ts.map +1 -0
  31. package/dist/protocol/request-stream.js +94 -0
  32. package/dist/protocol/request-stream.js.map +1 -0
  33. package/dist/protocol/session.d.ts +340 -0
  34. package/dist/protocol/session.d.ts.map +1 -0
  35. package/dist/protocol/session.js +908 -0
  36. package/dist/protocol/session.js.map +1 -0
  37. package/dist/protocol/stream-reset.d.ts +10 -0
  38. package/dist/protocol/stream-reset.d.ts.map +1 -0
  39. package/dist/protocol/stream-reset.js +24 -0
  40. package/dist/protocol/stream-reset.js.map +1 -0
  41. package/dist/protocol/subgroup-writer.d.ts +67 -0
  42. package/dist/protocol/subgroup-writer.d.ts.map +1 -0
  43. package/dist/protocol/subgroup-writer.js +172 -0
  44. package/dist/protocol/subgroup-writer.js.map +1 -0
  45. package/dist/protocol/transport-error.d.ts +29 -0
  46. package/dist/protocol/transport-error.d.ts.map +1 -0
  47. package/dist/protocol/transport-error.js +39 -0
  48. package/dist/protocol/transport-error.js.map +1 -0
  49. package/dist/protocol/varint.d.ts +20 -0
  50. package/dist/protocol/varint.d.ts.map +1 -0
  51. package/dist/protocol/varint.js +99 -0
  52. package/dist/protocol/varint.js.map +1 -0
  53. package/dist/track-source.d.ts +13 -0
  54. package/dist/track-source.d.ts.map +1 -0
  55. package/dist/track-source.js +2 -0
  56. package/dist/track-source.js.map +1 -0
  57. package/package.json +31 -4
@@ -0,0 +1,1146 @@
1
+ /**
2
+ * MOQT control-message wire codecs (moq-transport draft-22 §9).
3
+ *
4
+ * Every control or request-stream message is framed as:
5
+ *
6
+ * MOQT Control Message {
7
+ * Message Type (vi64),
8
+ * Message Length (16),
9
+ * Message Body (..),
10
+ * }
11
+ *
12
+ * Scope follows the subscribe-only engine: the encoders cover what a subscriber sends (SETUP, SUBSCRIBE, FETCH,
13
+ * TRACK_STATUS, SUBSCRIBE_NAMESPACE, REQUEST_UPDATE, GOAWAY, and REQUEST_OK / REQUEST_ERROR responses to incoming
14
+ * PUBLISH); the decoders cover what it receives. All draft-version specifics live in this directory — this is the
15
+ * churn-absorption layer for pre-WGLC drafts.
16
+ *
17
+ * Where the draft text and the deployed relay (moq-relay, moq-dev/moq) disagree on a wire detail, the codec follows the
18
+ * relay and says so at the site — interop is with the relay, not the prose.
19
+ *
20
+ * Namespace fields and track names are byte strings on the wire; this codec surfaces them as UTF-8 `string`s, which is
21
+ * what MSF (the streaming format this engine speaks) constrains them to.
22
+ */
23
+ import { ByteReader, ByteWriter, utf8Decode, utf8Encode } from './bytes.js';
24
+ import { MoqtProtocolError } from './errors.js';
25
+ import { decodeVarint, MAX_VARINT_VALUE } from './varint.js';
26
+ // ============================================================================
27
+ // Wire constants
28
+ // ============================================================================
29
+ /**
30
+ * ALPN / WebTransport protocol identifiers the core implements, in the order a client offers them (§6.2: `moqt-` plus
31
+ * the draft number). Version negotiation happens at connection time (`WT-Available-Protocols` in WebTransport, ALPN in
32
+ * native QUIC) — not in SETUP. Draft-22 is the default; draft-20 stays as a fallback for a peer that does not speak
33
+ * draft-22. The two differ on the wire only in the LOCATION_FILTER parameter (§9.20.9), so one codec serves both, and
34
+ * every function that encodes or decodes message parameters takes the negotiated identifier.
35
+ */
36
+ export const MOQT_PROTOCOL_IDS = ['moqt-22', 'moqt-20'];
37
+ /** The preferred protocol identifier, and the codec's default when a caller names none. */
38
+ export const MOQT_PROTOCOL_ID = 'moqt-22';
39
+ /**
40
+ * The codec for a transport's negotiated `protocol`. The SDK's connecting layer refuses any protocol outside
41
+ * `MOQT_PROTOCOL_IDS` before a session starts (spec/transport-adapter.md TA-8), so a value outside it here (a test
42
+ * transport, or an embedder's transport that cannot report one) gets the default, `moqt-22`.
43
+ */
44
+ export function resolveMoqtProtocol(protocol) {
45
+ return protocol !== undefined && MOQT_PROTOCOL_IDS.includes(protocol)
46
+ ? protocol
47
+ : MOQT_PROTOCOL_ID;
48
+ }
49
+ /** Control/request message type codes (§9, Table 5). */
50
+ export const MESSAGE_TYPE = {
51
+ SETUP: 0x2f00,
52
+ GOAWAY: 0x10,
53
+ SUBSCRIBE: 0x3,
54
+ SUBSCRIBE_OK: 0x4,
55
+ REQUEST_ERROR: 0x5,
56
+ PUBLISH_NAMESPACE: 0x6,
57
+ REQUEST_OK: 0x7,
58
+ NAMESPACE: 0x8,
59
+ PUBLISH_DONE: 0xb,
60
+ TRACK_STATUS: 0xd,
61
+ NAMESPACE_DONE: 0xe,
62
+ PUBLISH_SKIPPED: 0xf,
63
+ FETCH: 0x16,
64
+ FETCH_OK: 0x18,
65
+ PUBLISH: 0x1d,
66
+ PUBLISH_STATE_NOTIFY: 0x22,
67
+ REQUEST_UPDATE: 0x2,
68
+ SUBSCRIBE_NAMESPACE: 0x50,
69
+ SUBSCRIBE_TRACKS: 0x51,
70
+ };
71
+ /**
72
+ * Setup Option types (§9.1). A namespace separate from message parameters. A session sends
73
+ * options of these types through its `setupOptions` config, beside the MOQT_IMPLEMENTATION it adds
74
+ * itself.
75
+ */
76
+ export const SETUP_OPTION = {
77
+ /** The endpoint's path and query, sent only on native QUIC (§9.1.2). */
78
+ PATH: 0x01,
79
+ /** A token authorizing the session (§9.1.4). */
80
+ AUTHORIZATION_TOKEN: 0x03,
81
+ /** How many bytes of registered tokens the sender will cache (§9.1.3). */
82
+ MAX_AUTH_TOKEN_CACHE_SIZE: 0x04,
83
+ /** The endpoint's host and port, sent only on native QUIC (§9.1.1). */
84
+ AUTHORITY: 0x05,
85
+ /** The most ranges the sender accepts in one location filter (§9.1.6). */
86
+ MAX_FILTER_RANGES: 0x06,
87
+ /** The sender's implementation name (§9.1.5). */
88
+ MOQT_IMPLEMENTATION: 0x07,
89
+ /** The most REQUEST_UPDATE messages the sender accepts unanswered on one request stream (§9.1.7). */
90
+ MAX_REQUEST_UPDATES: 0x08,
91
+ /**
92
+ * The MoQ Solicit extension (draft-lcurley-moq-solicit-00), not a draft-22 option: `1` asks the peer to advertise
93
+ * namespaces only on a SUBSCRIBE_NAMESPACE, never as unsolicited PUBLISH_NAMESPACE. moq-relay honors it from 0.17.0.
94
+ * Even, so the value is a bare varint.
95
+ */
96
+ SOLICIT: 0x40b5a,
97
+ };
98
+ /** Message parameter types (§9.20, §16.7). */
99
+ export const PARAMETER_TYPE = {
100
+ OBJECT_DELIVERY_TIMEOUT: 0x02,
101
+ AUTHORIZATION_TOKEN: 0x03,
102
+ RENDEZVOUS_TIMEOUT: 0x04,
103
+ SUBGROUP_DELIVERY_TIMEOUT: 0x06,
104
+ EXPIRES: 0x08,
105
+ LARGEST_OBJECT: 0x09,
106
+ FILL_TIMEOUT: 0x0a,
107
+ FORWARD: 0x10,
108
+ SUBSCRIBER_PRIORITY: 0x20,
109
+ LOCATION_FILTER: 0x21,
110
+ GROUP_ORDER: 0x22,
111
+ FILL_PARAMETERS: 0x23,
112
+ SUBGROUP_FILTER: 0x25,
113
+ OBJECTID_FILTER: 0x26,
114
+ PRIORITY_FILTER: 0x27,
115
+ OBJECT_PROPERTY_FILTER: 0x28,
116
+ TRACK_PROPERTY_FILTER: 0x29,
117
+ NEW_GROUP_REQUEST: 0x32,
118
+ TRACK_NAMESPACE_PREFIX: 0x34,
119
+ INCLUDE_PROPERTIES: 0x35,
120
+ };
121
+ /**
122
+ * Track Property types (§9.7) — the KVP block trailing SUBSCRIBE_OK / PUBLISH / FETCH_OK. A registry of its own,
123
+ * distinct from both Setup Options and message parameters.
124
+ */
125
+ export const TRACK_PROPERTY = {
126
+ /**
127
+ * Units-per-second for the track's object TIMESTAMP extensions. Declaring it in SUBSCRIBE_OK is what opts the track
128
+ * into timestamp forwarding on moq-lite-rs relays — without it they parse and discard the extensions and re-stamp
129
+ * frames on arrival.
130
+ */
131
+ TIMESCALE: 0x08,
132
+ };
133
+ /** REQUEST_ERROR codes (§16.11.2). */
134
+ export const REQUEST_ERROR_CODE = {
135
+ /** An implementation-specific or otherwise unclassified error. */
136
+ INTERNAL_ERROR: 0x0,
137
+ /** The requester is not authorized for this request. */
138
+ UNAUTHORIZED: 0x1,
139
+ /** The responder could not complete the request in time. */
140
+ TIMEOUT: 0x2,
141
+ /** The responder does not support this request. */
142
+ NOT_SUPPORTED: 0x3,
143
+ /** An authorization token could not be parsed. */
144
+ MALFORMED_AUTH_TOKEN: 0x4,
145
+ /** An authorization token has expired. */
146
+ EXPIRED_AUTH_TOKEN: 0x5,
147
+ /** The responder is going away and takes no new requests. */
148
+ GOING_AWAY: 0x6,
149
+ /** The responder is overloaded. */
150
+ EXCESSIVE_LOAD: 0x9,
151
+ /** The requested track or namespace does not exist (yet). */
152
+ DOES_NOT_EXIST: 0x10,
153
+ /** The requested range is invalid. */
154
+ INVALID_RANGE: 0x11,
155
+ /** The track is malformed and cannot be served as requested. */
156
+ MALFORMED_TRACK: 0x12,
157
+ /** The responder is not interested in what was offered. */
158
+ UNINTERESTED: 0x20,
159
+ /** The namespace prefix overlaps one already requested. */
160
+ PREFIX_OVERLAP: 0x30,
161
+ /** The track namespace is too large. */
162
+ NAMESPACE_TOO_LARGE: 0x31,
163
+ /** The request needs an extension the responder does not support. */
164
+ UNSUPPORTED_EXTENSION: 0x33,
165
+ /** The request should be made elsewhere; REQUEST_ERROR carries a {@link Redirect}. */
166
+ REDIRECT: 0x34,
167
+ /** The request's filters conflict with each other. */
168
+ CONFLICTING_FILTERS: 0x35,
169
+ /** A filter in the request is invalid. */
170
+ INVALID_FILTER: 0x36,
171
+ };
172
+ /** PUBLISH_DONE status codes (§12.4). */
173
+ export const PUBLISH_DONE_STATUS = {
174
+ /** An implementation-specific or otherwise unclassified error. */
175
+ INTERNAL_ERROR: 0x0,
176
+ /** The subscriber is no longer authorized. */
177
+ UNAUTHORIZED: 0x1,
178
+ /** The track ended. */
179
+ TRACK_ENDED: 0x2,
180
+ /** The publisher or relay is going away. */
181
+ GOING_AWAY: 0x4,
182
+ /** The subscriber fell too far behind the track. */
183
+ TOO_FAR_BEHIND: 0x5,
184
+ /** The subscription expired. */
185
+ EXPIRED: 0x6,
186
+ /** A REQUEST_UPDATE for the subscription could not be applied. */
187
+ UPDATE_FAILED: 0x8,
188
+ /** The publisher or relay is overloaded. */
189
+ EXCESSIVE_LOAD: 0x9,
190
+ /** The track is malformed. */
191
+ MALFORMED_TRACK: 0x12,
192
+ };
193
+ /**
194
+ * REQUEST_ERROR codes for which an identical retry can never succeed: the request or its credentials are wrong in a way
195
+ * that does not change between attempts. Everything else — including codes this table does not know — is treated as
196
+ * retryable, so a relay introducing a new transient code degrades to paced retries rather than a dead player.
197
+ * EXPIRED_AUTH_TOKEN is deliberately absent: it has its own refresh path wherever requests are retried.
198
+ */
199
+ const PERMANENT_REQUEST_ERROR_CODES = new Set([
200
+ REQUEST_ERROR_CODE.UNAUTHORIZED,
201
+ REQUEST_ERROR_CODE.NOT_SUPPORTED,
202
+ REQUEST_ERROR_CODE.MALFORMED_AUTH_TOKEN,
203
+ REQUEST_ERROR_CODE.INVALID_RANGE,
204
+ // The track cannot be served as requested; an identical resubscribe
205
+ // re-earns the rejection. A publisher fixing the track surfaces as a
206
+ // catalog update, which re-selects and re-subscribes through fresh state.
207
+ REQUEST_ERROR_CODE.MALFORMED_TRACK,
208
+ REQUEST_ERROR_CODE.UNINTERESTED,
209
+ REQUEST_ERROR_CODE.PREFIX_OVERLAP,
210
+ REQUEST_ERROR_CODE.NAMESPACE_TOO_LARGE,
211
+ REQUEST_ERROR_CODE.UNSUPPORTED_EXTENSION,
212
+ // Until session migration exists, the redirect target is unreachable and
213
+ // re-asking the same relay just re-earns the redirect.
214
+ REQUEST_ERROR_CODE.REDIRECT,
215
+ REQUEST_ERROR_CODE.CONFLICTING_FILTERS,
216
+ REQUEST_ERROR_CODE.INVALID_FILTER,
217
+ ]);
218
+ /**
219
+ * Whether a failed request is worth re-issuing unchanged after a backoff. The transient family (`DOES_NOT_EXIST` while
220
+ * a broadcast has not started, `TIMEOUT`, `INTERNAL_ERROR`, overload, `GOING_AWAY`) reflects relay or publisher _state_
221
+ * that time can fix; the permanent family reflects the request itself and loops forever if retried.
222
+ */
223
+ export function isRetryableRequestErrorCode(errorCode) {
224
+ return !PERMANENT_REQUEST_ERROR_CODES.has(errorCode);
225
+ }
226
+ /**
227
+ * PUBLISH_DONE statuses after which an identical re-subscribe can never succeed: auth-shaped ends (same credentials the
228
+ * relay just rejected) and a malformed track (same request re-earns the same end; a publisher fix arrives as a catalog
229
+ * update through fresh state). Every other status describes publisher/relay state a broadcaster restart or live-edge
230
+ * rejoin legitimately recovers from (`TRACK_ENDED`, `GOING_AWAY`, `TOO_FAR_BEHIND`, overload, …), and unknown statuses
231
+ * degrade to paced retries for the same reason as {@link isRetryableRequestErrorCode}.
232
+ */
233
+ const PERMANENT_PUBLISH_DONE_STATUSES = new Set([
234
+ PUBLISH_DONE_STATUS.UNAUTHORIZED,
235
+ PUBLISH_DONE_STATUS.EXPIRED,
236
+ PUBLISH_DONE_STATUS.MALFORMED_TRACK,
237
+ ]);
238
+ /**
239
+ * Whether a subscription that ended with PUBLISH_DONE `statusCode` is worth re-subscribing. Every status but the
240
+ * permanent ones (`UNAUTHORIZED`, `EXPIRED`, `MALFORMED_TRACK`) is.
241
+ */
242
+ export function isRetryablePublishDoneStatus(statusCode) {
243
+ return !PERMANENT_PUBLISH_DONE_STATUSES.has(statusCode);
244
+ }
245
+ /** Stream reset / STOP_SENDING error codes (§12.5). */
246
+ export const STREAM_RESET_CODE = {
247
+ INTERNAL_ERROR: 0x0,
248
+ CANCELLED: 0x1,
249
+ DELIVERY_TIMEOUT: 0x2,
250
+ SESSION_CLOSED: 0x3,
251
+ GOING_AWAY: 0x4,
252
+ TOO_FAR_BEHIND: 0x5,
253
+ UNKNOWN_OBJECT_STATUS: 0x6,
254
+ EXPIRED_AUTH_TOKEN: 0x7,
255
+ EXCESSIVE_LOAD: 0x9,
256
+ MALFORMED_TRACK: 0x12,
257
+ };
258
+ /** Maximum body size — the frame length field is 16 bits. */
259
+ export const MAX_CONTROL_MESSAGE_LENGTH = 0xffff;
260
+ /** Most fields a track namespace may have; the codec rejects longer namespaces with `MoqtProtocolError`. */
261
+ export const MAX_NAMESPACE_FIELDS = 32;
262
+ const MAX_FULL_TRACK_NAME_LENGTH = 4096;
263
+ const MAX_REASON_PHRASE_LENGTH = 1024;
264
+ const MAX_NEW_SESSION_URI_LENGTH = 8192;
265
+ const MAX_KVP_VALUE_LENGTH = 0xffff;
266
+ const MAX_LOCATION_FILTER_FIELDS = 4;
267
+ /**
268
+ * Compare two Locations in Location order (§8.2): group first, then object. Negative when `a` precedes `b`, zero when
269
+ * they are equal, positive when `a` follows `b`, so it sorts with `Array.prototype.sort`.
270
+ */
271
+ export function compareLocations(a, b) {
272
+ return a.group - b.group || a.object - b.object;
273
+ }
274
+ function writeTrackNamespace(writer, namespace) {
275
+ if (namespace.length > MAX_NAMESPACE_FIELDS) {
276
+ throw new MoqtProtocolError(`track namespace has more than ${MAX_NAMESPACE_FIELDS} fields`);
277
+ }
278
+ writer.writeVarint(namespace.length);
279
+ for (const field of namespace) {
280
+ const bytes = utf8Encode(field);
281
+ if (bytes.length === 0)
282
+ throw new MoqtProtocolError('track namespace field must not be empty');
283
+ writer.writeLengthPrefixed(bytes);
284
+ }
285
+ }
286
+ function readTrackNamespace(reader) {
287
+ const fieldCount = reader.readVarint();
288
+ if (fieldCount > MAX_NAMESPACE_FIELDS) {
289
+ throw new MoqtProtocolError(`track namespace has more than ${MAX_NAMESPACE_FIELDS} fields`);
290
+ }
291
+ const namespace = [];
292
+ let totalLength = 0;
293
+ for (let i = 0; i < fieldCount; i++) {
294
+ const length = reader.readVarint();
295
+ if (length === 0)
296
+ throw new MoqtProtocolError('track namespace field must not be empty');
297
+ totalLength += length;
298
+ if (totalLength > MAX_FULL_TRACK_NAME_LENGTH) {
299
+ throw new MoqtProtocolError('track namespace exceeds 4096 bytes');
300
+ }
301
+ namespace.push(utf8Decode(reader.readBytes(length)));
302
+ }
303
+ return namespace;
304
+ }
305
+ function writeReasonPhrase(writer, reason) {
306
+ const bytes = utf8Encode(reason);
307
+ if (bytes.length > MAX_REASON_PHRASE_LENGTH)
308
+ throw new MoqtProtocolError('reason phrase exceeds 1024 bytes');
309
+ writer.writeLengthPrefixed(bytes);
310
+ }
311
+ function readReasonPhrase(reader) {
312
+ const length = reader.readVarint();
313
+ if (length > MAX_REASON_PHRASE_LENGTH)
314
+ throw new MoqtProtocolError('reason phrase exceeds 1024 bytes');
315
+ return utf8Decode(reader.readBytes(length));
316
+ }
317
+ function writeLocation(writer, location) {
318
+ writer.writeVarint(location.group);
319
+ writer.writeVarint(location.object);
320
+ }
321
+ function readLocation(reader) {
322
+ return { group: reader.readVarint(), object: reader.readVarint() };
323
+ }
324
+ /** LARGEST_OBJECT is two bare varints in draft-17 onward (§9.20), matching moq-relay 0.14.17 and 0.15.8 (moq-dev/moq#3561). */
325
+ function writeLocationParameter(writer, location) {
326
+ writeLocation(writer, location);
327
+ }
328
+ function readLocationParameter(reader) {
329
+ return readLocation(reader);
330
+ }
331
+ /** Serialize pairs in ascending type order with delta-encoded types. */
332
+ export function encodeKeyValuePairs(writer, pairs) {
333
+ const sorted = [...pairs].sort((a, b) => a.type - b.type);
334
+ let previousType = 0;
335
+ for (const { type, value } of sorted) {
336
+ writer.writeVarint(type - previousType);
337
+ previousType = type;
338
+ if (type % 2 === 0) {
339
+ if (typeof value !== 'number')
340
+ throw new MoqtProtocolError(`even KVP type ${type} requires a varint value`);
341
+ writer.writeVarint(value);
342
+ }
343
+ else {
344
+ if (typeof value === 'number')
345
+ throw new MoqtProtocolError(`odd KVP type ${type} requires a byte value`);
346
+ if (value.length > MAX_KVP_VALUE_LENGTH)
347
+ throw new MoqtProtocolError('KVP value exceeds 2^16-1 bytes');
348
+ writer.writeLengthPrefixed(value);
349
+ }
350
+ }
351
+ }
352
+ /** Parse pairs until `reader` reaches `endOffset` (KVP blocks are length-bounded). */
353
+ export function decodeKeyValuePairs(reader, endOffset) {
354
+ const pairs = [];
355
+ let previousType = 0;
356
+ while (reader.offset < endOffset) {
357
+ const type = previousType + reader.readVarint();
358
+ previousType = type;
359
+ if (type % 2 === 0) {
360
+ pairs.push({ type, value: reader.readVarint() });
361
+ }
362
+ else {
363
+ const length = reader.readVarint();
364
+ if (length > MAX_KVP_VALUE_LENGTH)
365
+ throw new MoqtProtocolError('KVP value exceeds 2^16-1 bytes');
366
+ pairs.push({ type, value: reader.readBytes(length) });
367
+ }
368
+ }
369
+ if (reader.offset !== endOffset)
370
+ throw new MoqtProtocolError('KVP block overran its bound');
371
+ return pairs;
372
+ }
373
+ /** Draft-22's Location Filter Type (§9.20.9, Table 6). */
374
+ const LOCATION_FILTER_TYPE = {
375
+ NONE: 0x00,
376
+ RELATIVE_START: 0x01,
377
+ ABSOLUTE_START: 0x02,
378
+ ABSOLUTE_START_GROUP_END: 0x03,
379
+ ABSOLUTE_RANGE: 0x04,
380
+ NEXT_OBJECT: 0x05,
381
+ };
382
+ /**
383
+ * Serialize a filter as the LOCATION_FILTER parameter's value as it follows the Parameter Type: on draft-22 the
384
+ * Location Filter Type and the fields it selects, on draft-20 the field list without its length prefix.
385
+ */
386
+ export function encodeLocationFilter(filter, protocol = MOQT_PROTOCOL_ID) {
387
+ const writer = new ByteWriter(32);
388
+ if (filter.type === 'absolute' && filter.endObject !== undefined && filter.endGroupDelta === undefined) {
389
+ throw new MoqtProtocolError('location filter end object requires an end group');
390
+ }
391
+ if (protocol === 'moqt-20') {
392
+ writeDraft20LocationFields(writer, filter);
393
+ }
394
+ else {
395
+ writeLocationFilter(writer, filter);
396
+ }
397
+ return writer.toBytes();
398
+ }
399
+ function writeLocationFilter(writer, filter) {
400
+ switch (filter.type) {
401
+ case 'none':
402
+ writer.writeVarint(LOCATION_FILTER_TYPE.NONE);
403
+ break;
404
+ case 'next-object':
405
+ writer.writeVarint(LOCATION_FILTER_TYPE.NEXT_OBJECT);
406
+ break;
407
+ case 'relative-group':
408
+ writer.writeVarint(LOCATION_FILTER_TYPE.RELATIVE_START);
409
+ writer.writeVarint(filter.groupsBeforeNext);
410
+ break;
411
+ case 'absolute': {
412
+ const { start, endGroupDelta, endObject } = filter;
413
+ let type = LOCATION_FILTER_TYPE.ABSOLUTE_START;
414
+ if (endObject !== undefined)
415
+ type = LOCATION_FILTER_TYPE.ABSOLUTE_RANGE;
416
+ else if (endGroupDelta !== undefined)
417
+ type = LOCATION_FILTER_TYPE.ABSOLUTE_START_GROUP_END;
418
+ writer.writeVarint(type);
419
+ writeLocation(writer, start);
420
+ if (endGroupDelta !== undefined)
421
+ writer.writeVarint(endGroupDelta);
422
+ if (endObject !== undefined)
423
+ writer.writeVarint(endObject);
424
+ break;
425
+ }
426
+ }
427
+ }
428
+ function writeDraft20LocationFields(writer, filter) {
429
+ switch (filter.type) {
430
+ case 'none':
431
+ break;
432
+ case 'next-object':
433
+ writer.writeVarint(0);
434
+ writer.writeVarint(0);
435
+ break;
436
+ case 'relative-group':
437
+ writer.writeVarint(filter.groupsBeforeNext);
438
+ break;
439
+ case 'absolute': {
440
+ const { start, endGroupDelta, endObject } = filter;
441
+ if (start.group === 0 && start.object === 0 && endGroupDelta === undefined)
442
+ break;
443
+ writeLocation(writer, start);
444
+ if (endGroupDelta !== undefined)
445
+ writer.writeVarint(endGroupDelta);
446
+ if (endObject !== undefined)
447
+ writer.writeVarint(endObject);
448
+ break;
449
+ }
450
+ }
451
+ }
452
+ /** Decode a LOCATION_FILTER value as `encodeLocationFilter` produces it; every byte must belong to the filter. */
453
+ export function decodeLocationFilter(bytes, protocol = MOQT_PROTOCOL_ID) {
454
+ if (protocol === 'moqt-20')
455
+ return decodeDraft20LocationFields(bytes);
456
+ const reader = new ByteReader(bytes);
457
+ const filter = readLocationFilter(reader);
458
+ if (reader.remaining > 0)
459
+ throw new MoqtProtocolError('location filter has trailing bytes');
460
+ return filter;
461
+ }
462
+ /** Read a draft-22 LOCATION_FILTER value, which delimits itself: its type says how many fields follow. */
463
+ function readLocationFilter(reader) {
464
+ const type = reader.readVarint();
465
+ switch (type) {
466
+ case LOCATION_FILTER_TYPE.NONE:
467
+ return { type: 'none' };
468
+ case LOCATION_FILTER_TYPE.RELATIVE_START:
469
+ return { type: 'relative-group', groupsBeforeNext: reader.readVarint() };
470
+ case LOCATION_FILTER_TYPE.NEXT_OBJECT:
471
+ return { type: 'next-object' };
472
+ case LOCATION_FILTER_TYPE.ABSOLUTE_START:
473
+ case LOCATION_FILTER_TYPE.ABSOLUTE_START_GROUP_END:
474
+ case LOCATION_FILTER_TYPE.ABSOLUTE_RANGE: {
475
+ const filter = { type: 'absolute', start: readLocation(reader) };
476
+ if (type === LOCATION_FILTER_TYPE.ABSOLUTE_START)
477
+ return filter;
478
+ filter.endGroupDelta = readEndGroupDelta(reader, filter.start.group);
479
+ if (type === LOCATION_FILTER_TYPE.ABSOLUTE_RANGE)
480
+ filter.endObject = reader.readVarint();
481
+ return filter;
482
+ }
483
+ default:
484
+ // §9.20.9: any other Location Filter Type is a PROTOCOL_VIOLATION.
485
+ throw new MoqtProtocolError(`unknown Location Filter Type ${type}`);
486
+ }
487
+ }
488
+ function readEndGroupDelta(reader, startGroup) {
489
+ const endGroupDelta = reader.readVarint();
490
+ if (startGroup + endGroupDelta > MAX_VARINT_VALUE) {
491
+ throw new MoqtProtocolError('location filter end group exceeds supported range');
492
+ }
493
+ return endGroupDelta;
494
+ }
495
+ function decodeDraft20LocationFields(bytes) {
496
+ const reader = new ByteReader(bytes);
497
+ const fields = [];
498
+ while (reader.remaining > 0) {
499
+ if (fields.length === MAX_LOCATION_FILTER_FIELDS) {
500
+ throw new MoqtProtocolError('location filter has more than four fields');
501
+ }
502
+ fields.push(reader.readVarint());
503
+ }
504
+ if (fields.length === 0)
505
+ return { type: 'none' };
506
+ if (fields.length === 1)
507
+ return { type: 'relative-group', groupsBeforeNext: fields[0] };
508
+ const [group, object, endGroupDelta, endObject] = fields;
509
+ if (fields.length === 2 && group === 0 && object === 0)
510
+ return { type: 'next-object' };
511
+ const filter = { type: 'absolute', start: { group, object } };
512
+ if (endGroupDelta !== undefined) {
513
+ if (group + endGroupDelta > MAX_VARINT_VALUE) {
514
+ throw new MoqtProtocolError('location filter end group exceeds supported range');
515
+ }
516
+ filter.endGroupDelta = endGroupDelta;
517
+ }
518
+ if (endObject !== undefined)
519
+ filter.endObject = endObject;
520
+ return filter;
521
+ }
522
+ /**
523
+ * Whether a Location filter, evaluated with the fetch rules of §9.20.9, selects no Objects. A fetch range, and so a
524
+ * subscription's fill range (§3.4), never extends beyond Largest Object: with no Largest Object nothing exists to fetch,
525
+ * the Next Object and the Next Group both lie past it, an absolute start past it selects nothing, and a bounded
526
+ * absolute range whose end precedes its start is empty. A publisher opens no fill fetch stream for an empty range.
527
+ *
528
+ * @param filter - The fill range's filter: the one inside FILL_PARAMETERS, else the subscription's, else `none`.
529
+ * @param largestObject - The track's Largest Object, `undefined` when nothing has been published yet.
530
+ */
531
+ export function isEmptyFetchRange(filter, largestObject) {
532
+ if (largestObject === undefined)
533
+ return true;
534
+ switch (filter.type) {
535
+ case 'none':
536
+ return false;
537
+ case 'next-object':
538
+ return true;
539
+ case 'relative-group':
540
+ return filter.groupsBeforeNext === 0;
541
+ case 'absolute': {
542
+ const { start, endGroupDelta, endObject } = filter;
543
+ if (compareLocations(start, largestObject) > 0)
544
+ return true;
545
+ // The end group is a non-negative delta from the start group, so only a same-group end can precede the start.
546
+ return endGroupDelta === 0 && endObject !== undefined && endObject < start.object;
547
+ }
548
+ }
549
+ }
550
+ const FILL_SCOPE_TYPES = new Set([
551
+ PARAMETER_TYPE.FILL_TIMEOUT,
552
+ PARAMETER_TYPE.SUBSCRIBER_PRIORITY,
553
+ PARAMETER_TYPE.LOCATION_FILTER,
554
+ PARAMETER_TYPE.GROUP_ORDER,
555
+ PARAMETER_TYPE.SUBGROUP_FILTER,
556
+ PARAMETER_TYPE.OBJECTID_FILTER,
557
+ PARAMETER_TYPE.PRIORITY_FILTER,
558
+ PARAMETER_TYPE.OBJECT_PROPERTY_FILTER,
559
+ ]);
560
+ const GROUP_ORDER_WIRE = { ascending: 0x1, descending: 0x2 };
561
+ function collectParameterEntries(parameters, protocol) {
562
+ const entries = [];
563
+ const push = (type, write) => entries.push({ type, write });
564
+ if (parameters.objectDeliveryTimeout !== undefined) {
565
+ push(PARAMETER_TYPE.OBJECT_DELIVERY_TIMEOUT, (w) => w.writeVarint(parameters.objectDeliveryTimeout));
566
+ }
567
+ if (parameters.subgroupDeliveryTimeout !== undefined) {
568
+ push(PARAMETER_TYPE.SUBGROUP_DELIVERY_TIMEOUT, (w) => w.writeVarint(parameters.subgroupDeliveryTimeout));
569
+ }
570
+ if (parameters.rendezvousTimeout !== undefined) {
571
+ push(PARAMETER_TYPE.RENDEZVOUS_TIMEOUT, (w) => w.writeVarint(parameters.rendezvousTimeout));
572
+ }
573
+ if (parameters.fillTimeout !== undefined) {
574
+ push(PARAMETER_TYPE.FILL_TIMEOUT, (w) => w.writeVarint(parameters.fillTimeout));
575
+ }
576
+ for (const token of parameters.authorizationTokens ?? []) {
577
+ push(PARAMETER_TYPE.AUTHORIZATION_TOKEN, (w) => w.writeLengthPrefixed(token));
578
+ }
579
+ if (parameters.expires !== undefined) {
580
+ push(PARAMETER_TYPE.EXPIRES, (w) => w.writeVarint(parameters.expires));
581
+ }
582
+ if (parameters.largestObject !== undefined) {
583
+ push(PARAMETER_TYPE.LARGEST_OBJECT, (w) => writeLocationParameter(w, parameters.largestObject));
584
+ }
585
+ if (parameters.forward !== undefined) {
586
+ push(PARAMETER_TYPE.FORWARD, (w) => w.writeUint8(parameters.forward));
587
+ }
588
+ if (parameters.subscriberPriority !== undefined) {
589
+ push(PARAMETER_TYPE.SUBSCRIBER_PRIORITY, (w) => w.writeUint8(parameters.subscriberPriority));
590
+ }
591
+ if (parameters.locationFilter !== undefined) {
592
+ push(PARAMETER_TYPE.LOCATION_FILTER, (w) => {
593
+ const value = encodeLocationFilter(parameters.locationFilter, protocol);
594
+ // Draft-20 length-prefixes the field list; draft-22's Location Filter Type delimits it (§9.20.9).
595
+ if (protocol === 'moqt-20')
596
+ w.writeLengthPrefixed(value);
597
+ else
598
+ w.writeBytes(value);
599
+ });
600
+ }
601
+ if (parameters.groupOrder !== undefined) {
602
+ push(PARAMETER_TYPE.GROUP_ORDER, (w) => w.writeUint8(GROUP_ORDER_WIRE[parameters.groupOrder]));
603
+ }
604
+ if (parameters.fillParameters !== undefined) {
605
+ push(PARAMETER_TYPE.FILL_PARAMETERS, (w) => w.writeLengthPrefixed(encodeFillParameters(parameters.fillParameters, protocol)));
606
+ }
607
+ if (parameters.newGroupRequest !== undefined) {
608
+ push(PARAMETER_TYPE.NEW_GROUP_REQUEST, (w) => w.writeVarint(parameters.newGroupRequest));
609
+ }
610
+ for (const filter of parameters.rangeFilters ?? []) {
611
+ push(filter.type, (w) => w.writeLengthPrefixed(filter.value));
612
+ }
613
+ if (parameters.trackNamespacePrefix !== undefined) {
614
+ push(PARAMETER_TYPE.TRACK_NAMESPACE_PREFIX, (w) => writeTrackNamespace(w, parameters.trackNamespacePrefix));
615
+ }
616
+ if (parameters.includeProperties !== undefined) {
617
+ push(PARAMETER_TYPE.INCLUDE_PROPERTIES, (w) => w.writeUint8(parameters.includeProperties));
618
+ }
619
+ return entries;
620
+ }
621
+ /**
622
+ * Serialize as `Number of Parameters (vi64)` + delta-typed parameter list. The `'fill'` scope is the nested list inside
623
+ * FILL_PARAMETERS, where only Table 7's types are legal.
624
+ */
625
+ export function encodeMessageParameters(writer, parameters = {}, protocol = MOQT_PROTOCOL_ID, scope = 'message') {
626
+ const entries = collectParameterEntries(parameters, protocol).sort((a, b) => a.type - b.type);
627
+ if (scope === 'fill') {
628
+ const disallowed = entries.find((entry) => !FILL_SCOPE_TYPES.has(entry.type));
629
+ if (disallowed) {
630
+ throw new MoqtProtocolError(`parameter type ${disallowed.type} is not allowed inside FILL_PARAMETERS`);
631
+ }
632
+ }
633
+ writer.writeVarint(entries.length);
634
+ let previousType = 0;
635
+ for (const entry of entries) {
636
+ writer.writeVarint(entry.type - previousType);
637
+ previousType = entry.type;
638
+ entry.write(writer);
639
+ }
640
+ }
641
+ /** FILL_PARAMETERS' value: a parameter list encoded as if for a separate message (§9.20.15). */
642
+ function encodeFillParameters(fill, protocol) {
643
+ const writer = new ByteWriter(64);
644
+ encodeMessageParameters(writer, fill, protocol, 'fill');
645
+ return writer.toBytes();
646
+ }
647
+ const RANGE_FILTER_TYPES = [
648
+ PARAMETER_TYPE.SUBGROUP_FILTER,
649
+ PARAMETER_TYPE.OBJECTID_FILTER,
650
+ PARAMETER_TYPE.PRIORITY_FILTER,
651
+ PARAMETER_TYPE.OBJECT_PROPERTY_FILTER,
652
+ PARAMETER_TYPE.TRACK_PROPERTY_FILTER,
653
+ ];
654
+ export function decodeMessageParameters(reader, protocol = MOQT_PROTOCOL_ID, scope = 'message') {
655
+ const count = reader.readVarint();
656
+ const parameters = {};
657
+ let previousType = 0;
658
+ for (let i = 0; i < count; i++) {
659
+ const type = previousType + reader.readVarint();
660
+ previousType = type;
661
+ // §9.20.15: a type outside Table 7 inside FILL_PARAMETERS is a
662
+ // PROTOCOL_VIOLATION, the nested scope included.
663
+ if (scope === 'fill' && !FILL_SCOPE_TYPES.has(type)) {
664
+ throw new MoqtProtocolError(`parameter type ${type} is not allowed inside FILL_PARAMETERS`);
665
+ }
666
+ switch (type) {
667
+ case PARAMETER_TYPE.OBJECT_DELIVERY_TIMEOUT:
668
+ parameters.objectDeliveryTimeout = reader.readVarint();
669
+ break;
670
+ case PARAMETER_TYPE.SUBGROUP_DELIVERY_TIMEOUT:
671
+ parameters.subgroupDeliveryTimeout = reader.readVarint();
672
+ break;
673
+ case PARAMETER_TYPE.RENDEZVOUS_TIMEOUT:
674
+ parameters.rendezvousTimeout = reader.readVarint();
675
+ break;
676
+ case PARAMETER_TYPE.FILL_TIMEOUT:
677
+ parameters.fillTimeout = reader.readVarint();
678
+ break;
679
+ case PARAMETER_TYPE.AUTHORIZATION_TOKEN: {
680
+ const token = reader.readBytes(reader.readVarint());
681
+ parameters.authorizationTokens ??= [];
682
+ parameters.authorizationTokens.push(token);
683
+ break;
684
+ }
685
+ case PARAMETER_TYPE.EXPIRES:
686
+ parameters.expires = reader.readVarint();
687
+ break;
688
+ case PARAMETER_TYPE.LARGEST_OBJECT:
689
+ parameters.largestObject = readLocationParameter(reader);
690
+ break;
691
+ case PARAMETER_TYPE.FORWARD: {
692
+ const forward = reader.readUint8();
693
+ if (forward !== 0 && forward !== 1)
694
+ throw new MoqtProtocolError(`invalid FORWARD value ${forward}`);
695
+ parameters.forward = forward;
696
+ break;
697
+ }
698
+ case PARAMETER_TYPE.SUBSCRIBER_PRIORITY:
699
+ parameters.subscriberPriority = reader.readUint8();
700
+ break;
701
+ case PARAMETER_TYPE.LOCATION_FILTER:
702
+ parameters.locationFilter =
703
+ protocol === 'moqt-20'
704
+ ? decodeLocationFilter(reader.readBytes(reader.readVarint()), protocol)
705
+ : readLocationFilter(reader);
706
+ break;
707
+ case PARAMETER_TYPE.GROUP_ORDER: {
708
+ const order = reader.readUint8();
709
+ if (order !== 0x1 && order !== 0x2)
710
+ throw new MoqtProtocolError(`invalid GROUP_ORDER value ${order}`);
711
+ parameters.groupOrder = order === 0x1 ? 'ascending' : 'descending';
712
+ break;
713
+ }
714
+ case PARAMETER_TYPE.FILL_PARAMETERS: {
715
+ const value = new ByteReader(reader.readBytes(reader.readVarint()));
716
+ parameters.fillParameters = decodeMessageParameters(value, protocol, 'fill');
717
+ if (value.remaining !== 0)
718
+ throw new MoqtProtocolError('FILL_PARAMETERS has trailing bytes');
719
+ break;
720
+ }
721
+ case PARAMETER_TYPE.NEW_GROUP_REQUEST:
722
+ parameters.newGroupRequest = reader.readVarint();
723
+ break;
724
+ case PARAMETER_TYPE.TRACK_NAMESPACE_PREFIX:
725
+ parameters.trackNamespacePrefix = readTrackNamespace(reader);
726
+ break;
727
+ case PARAMETER_TYPE.INCLUDE_PROPERTIES: {
728
+ // §9.20.21: a uint8 with no Length, as moq-relay frames it since 0.17.0
729
+ // (0.15.8 and earlier added a Length by the odd-type parity rule).
730
+ const include = reader.readUint8();
731
+ if (include !== 0 && include !== 1)
732
+ throw new MoqtProtocolError(`invalid INCLUDE_PROPERTIES value ${include}`);
733
+ parameters.includeProperties = include;
734
+ break;
735
+ }
736
+ default: {
737
+ if (RANGE_FILTER_TYPES.includes(type)) {
738
+ const value = reader.readBytes(reader.readVarint());
739
+ parameters.rangeFilters ??= [];
740
+ parameters.rangeFilters.push({ type, value });
741
+ break;
742
+ }
743
+ // §9.20: unknown parameters cannot be skipped (the block is bounded
744
+ // by count, and the value encoding is per-type) — session error.
745
+ throw new MoqtProtocolError(`unknown message parameter type ${type}`);
746
+ }
747
+ }
748
+ }
749
+ return parameters;
750
+ }
751
+ // ============================================================================
752
+ // Authorization tokens (§9.20.2)
753
+ // ============================================================================
754
+ /**
755
+ * Serialize a Token structure with Alias Type USE_VALUE (0x3) — the stateless form the engine uses to attach an
756
+ * MSF-provided token to a request without alias registration.
757
+ */
758
+ export function encodeAuthTokenUseValue(tokenType, value) {
759
+ const writer = new ByteWriter(value.length + 8);
760
+ writer.writeVarint(0x3);
761
+ writer.writeVarint(tokenType);
762
+ writer.writeBytes(value);
763
+ return writer.toBytes();
764
+ }
765
+ function frameMessage(type, body) {
766
+ const bodyBytes = body.toBytes();
767
+ if (bodyBytes.length > MAX_CONTROL_MESSAGE_LENGTH) {
768
+ throw new MoqtProtocolError('control message exceeds 2^16-1 bytes');
769
+ }
770
+ const writer = new ByteWriter(bodyBytes.length + 8);
771
+ writer.writeVarint(type);
772
+ writer.writeUint16(bodyBytes.length);
773
+ writer.writeBytes(bodyBytes);
774
+ return writer.toBytes();
775
+ }
776
+ /**
777
+ * Incremental control-message deframer. Feed it stream chunks; it yields complete `ControlMessageFrame`s as they
778
+ * materialize. Used for both the control streams and request streams (same framing).
779
+ */
780
+ export class ControlMessageDeframer {
781
+ #buffer = new Uint8Array(0);
782
+ push(chunk) {
783
+ if (this.#buffer.length === 0) {
784
+ this.#buffer = chunk;
785
+ }
786
+ else {
787
+ const merged = new Uint8Array(this.#buffer.length + chunk.length);
788
+ merged.set(this.#buffer);
789
+ merged.set(chunk, this.#buffer.length);
790
+ this.#buffer = merged;
791
+ }
792
+ const frames = [];
793
+ let offset = 0;
794
+ while (true) {
795
+ const frame = this.#tryReadFrame(offset);
796
+ if (!frame)
797
+ break;
798
+ frames.push(frame.frame);
799
+ offset = frame.nextOffset;
800
+ }
801
+ this.#buffer = offset > 0 ? this.#buffer.subarray(offset) : this.#buffer;
802
+ return frames;
803
+ }
804
+ /** Bytes buffered but not yet forming a complete frame. */
805
+ get pendingBytes() {
806
+ return this.#buffer.length;
807
+ }
808
+ #tryReadFrame(offset) {
809
+ const buffer = this.#buffer;
810
+ if (offset >= buffer.length)
811
+ return null;
812
+ let type;
813
+ let headerLength;
814
+ try {
815
+ const decoded = decodeVarint(buffer, offset);
816
+ type = decoded.value;
817
+ headerLength = decoded.byteLength;
818
+ }
819
+ catch (error) {
820
+ // Incomplete varint — wait for more bytes.
821
+ if (error instanceof RangeError)
822
+ return null;
823
+ throw error;
824
+ }
825
+ if (offset + headerLength + 2 > buffer.length)
826
+ return null;
827
+ const length = buffer[offset + headerLength] * 256 + buffer[offset + headerLength + 1];
828
+ const bodyStart = offset + headerLength + 2;
829
+ if (bodyStart + length > buffer.length)
830
+ return null;
831
+ return {
832
+ frame: { type, body: buffer.slice(bodyStart, bodyStart + length) },
833
+ nextOffset: bodyStart + length,
834
+ };
835
+ }
836
+ }
837
+ // ============================================================================
838
+ // Encoders (subscriber → publisher)
839
+ // ============================================================================
840
+ /** SETUP (§9.1) — first message on the endpoint's control stream. */
841
+ export function encodeSetup(options = []) {
842
+ const body = new ByteWriter();
843
+ encodeKeyValuePairs(body, options);
844
+ return frameMessage(MESSAGE_TYPE.SETUP, body);
845
+ }
846
+ /** SUBSCRIBE, TRACK_STATUS, and FETCH share one body: Request ID, Full Track Name, Parameters. */
847
+ function encodeTrackRequest(type, request, protocol) {
848
+ const body = new ByteWriter();
849
+ body.writeVarint(request.requestId);
850
+ writeTrackNamespace(body, request.trackNamespace);
851
+ body.writeLengthPrefixed(utf8Encode(request.trackName));
852
+ encodeMessageParameters(body, request.parameters, protocol);
853
+ return frameMessage(type, body);
854
+ }
855
+ /** SUBSCRIBE (§9.6) — first message on a new request stream. */
856
+ export function encodeSubscribe(request, protocol = MOQT_PROTOCOL_ID) {
857
+ return encodeTrackRequest(MESSAGE_TYPE.SUBSCRIBE, request, protocol);
858
+ }
859
+ /** TRACK_STATUS (§9.13) — identical wire format to SUBSCRIBE. */
860
+ export function encodeTrackStatus(request, protocol = MOQT_PROTOCOL_ID) {
861
+ return encodeTrackRequest(MESSAGE_TYPE.TRACK_STATUS, request, protocol);
862
+ }
863
+ /** FETCH (§9.11) — first message on a new request stream. */
864
+ export function encodeFetch(request, protocol = MOQT_PROTOCOL_ID) {
865
+ return encodeTrackRequest(MESSAGE_TYPE.FETCH, request, protocol);
866
+ }
867
+ /** SUBSCRIBE_NAMESPACE (§9.15) — first message on a new request stream. */
868
+ export function encodeSubscribeNamespace(request, protocol = MOQT_PROTOCOL_ID) {
869
+ const body = new ByteWriter();
870
+ body.writeVarint(request.requestId);
871
+ writeTrackNamespace(body, request.trackNamespacePrefix);
872
+ encodeMessageParameters(body, request.parameters, protocol);
873
+ return frameMessage(MESSAGE_TYPE.SUBSCRIBE_NAMESPACE, body);
874
+ }
875
+ /**
876
+ * REQUEST_UPDATE (§9.5) — sent on an existing request stream. `requestId` is the update's own, freshly allocated
877
+ * Request ID (§6.4.2.1 counts REQUEST_UPDATE among the messages that consume one); the stream identifies the request being
878
+ * updated.
879
+ */
880
+ export function encodeRequestUpdate(requestId, parameters = {}, protocol = MOQT_PROTOCOL_ID) {
881
+ const body = new ByteWriter();
882
+ body.writeVarint(requestId);
883
+ encodeMessageParameters(body, parameters, protocol);
884
+ return frameMessage(MESSAGE_TYPE.REQUEST_UPDATE, body);
885
+ }
886
+ /**
887
+ * GOAWAY (§9.2). Clients MUST send a zero-length New Session URI, so the encoder takes only the timeout (milliseconds;
888
+ * 0 = no specific timeout).
889
+ */
890
+ export function encodeGoaway(timeout = 0) {
891
+ const body = new ByteWriter();
892
+ body.writeVarint(0);
893
+ body.writeVarint(timeout);
894
+ return frameMessage(MESSAGE_TYPE.GOAWAY, body);
895
+ }
896
+ /**
897
+ * REQUEST_OK (§9.3). The subscriber sends this to accept an incoming PUBLISH (PUBLISH_OK). Track Properties are always
898
+ * empty in that role, and since draft-20 so are the parameters — a subscriber changes subscription parameters with
899
+ * REQUEST_UPDATE, not in PUBLISH_OK (§9.8); the session driver's `accept()` therefore takes none. The parameter slot
900
+ * stays for the publisher-side roles of REQUEST_OK (TRACK_STATUS_OK, REQUEST_UPDATE_OK), which the fake peer in tests
901
+ * exercises.
902
+ */
903
+ export function encodeRequestOk(parameters = {}, protocol = MOQT_PROTOCOL_ID) {
904
+ const body = new ByteWriter();
905
+ encodeMessageParameters(body, parameters, protocol);
906
+ return frameMessage(MESSAGE_TYPE.REQUEST_OK, body);
907
+ }
908
+ /** REQUEST_ERROR (§9.4) without a Redirect — enough to reject incoming requests. */
909
+ export function encodeRequestError(errorCode, reason = '', retryInterval = 0) {
910
+ const body = new ByteWriter();
911
+ body.writeVarint(errorCode);
912
+ body.writeVarint(retryInterval);
913
+ writeReasonPhrase(body, reason);
914
+ return frameMessage(MESSAGE_TYPE.REQUEST_ERROR, body);
915
+ }
916
+ // ============================================================================
917
+ // Encoders (publisher → subscriber)
918
+ //
919
+ // The engine is subscribe-only, but the codec is symmetric: these are used
920
+ // by the in-memory fake peer in tests (the same seam a future publish
921
+ // path would build on).
922
+ // ============================================================================
923
+ /** SUBSCRIBE_OK (§9.7). */
924
+ export function encodeSubscribeOk(trackAlias, parameters = {}, trackProperties = [], protocol = MOQT_PROTOCOL_ID) {
925
+ const body = new ByteWriter();
926
+ body.writeVarint(trackAlias);
927
+ encodeMessageParameters(body, parameters, protocol);
928
+ encodeKeyValuePairs(body, trackProperties);
929
+ return frameMessage(MESSAGE_TYPE.SUBSCRIBE_OK, body);
930
+ }
931
+ /** PUBLISH_DONE (§9.9). */
932
+ export function encodePublishDone(statusCode, streamCount, reason = '') {
933
+ const body = new ByteWriter();
934
+ body.writeVarint(statusCode);
935
+ body.writeVarint(streamCount);
936
+ writeReasonPhrase(body, reason);
937
+ return frameMessage(MESSAGE_TYPE.PUBLISH_DONE, body);
938
+ }
939
+ /** PUBLISH_STATE_NOTIFY (§9.10) — the publisher's unilateral "these subscription parameters changed". */
940
+ export function encodePublishStateNotify(parameters = {}, protocol = MOQT_PROTOCOL_ID) {
941
+ const body = new ByteWriter();
942
+ encodeMessageParameters(body, parameters, protocol);
943
+ return frameMessage(MESSAGE_TYPE.PUBLISH_STATE_NOTIFY, body);
944
+ }
945
+ /** FETCH_OK (§9.12). */
946
+ export function encodeFetchOk(endOfTrack, endLocation, parameters = {}, trackProperties = [], protocol = MOQT_PROTOCOL_ID) {
947
+ const body = new ByteWriter();
948
+ body.writeUint8(endOfTrack ? 1 : 0);
949
+ writeLocation(body, endLocation);
950
+ encodeMessageParameters(body, parameters, protocol);
951
+ encodeKeyValuePairs(body, trackProperties);
952
+ return frameMessage(MESSAGE_TYPE.FETCH_OK, body);
953
+ }
954
+ /** PUBLISH (§9.8). */
955
+ export function encodePublish(request, trackProperties = [], protocol = MOQT_PROTOCOL_ID) {
956
+ const body = new ByteWriter();
957
+ body.writeVarint(request.requestId);
958
+ writeTrackNamespace(body, request.trackNamespace);
959
+ body.writeLengthPrefixed(utf8Encode(request.trackName));
960
+ body.writeVarint(request.trackAlias);
961
+ encodeMessageParameters(body, request.parameters, protocol);
962
+ encodeKeyValuePairs(body, trackProperties);
963
+ return frameMessage(MESSAGE_TYPE.PUBLISH, body);
964
+ }
965
+ /** PUBLISH_NAMESPACE (§9.14) — a publisher announcing a namespace. */
966
+ export function encodePublishNamespace(request, protocol = MOQT_PROTOCOL_ID) {
967
+ const body = new ByteWriter();
968
+ body.writeVarint(request.requestId);
969
+ writeTrackNamespace(body, request.trackNamespace);
970
+ encodeMessageParameters(body, request.parameters, protocol);
971
+ return frameMessage(MESSAGE_TYPE.PUBLISH_NAMESPACE, body);
972
+ }
973
+ /**
974
+ * NAMESPACE (§9.16) — announce one namespace on an accepted inbound SUBSCRIBE_NAMESPACE request stream. The body is
975
+ * the namespace suffix relative to that stream's subscribed prefix and nothing else: peers bound-check the tuple
976
+ * against the frame length (moq-lite-rs treats even a zero parameter count as a malformed entry and kills the announce
977
+ * stream), so no parameter block is written.
978
+ */
979
+ export function encodeNamespace(trackNamespaceSuffix) {
980
+ const body = new ByteWriter();
981
+ writeTrackNamespace(body, trackNamespaceSuffix);
982
+ return frameMessage(MESSAGE_TYPE.NAMESPACE, body);
983
+ }
984
+ /** NAMESPACE_DONE (§9.17) — retract a NAMESPACE announcement (same body shape). */
985
+ export function encodeNamespaceDone(trackNamespaceSuffix) {
986
+ const body = new ByteWriter();
987
+ writeTrackNamespace(body, trackNamespaceSuffix);
988
+ return frameMessage(MESSAGE_TYPE.NAMESPACE_DONE, body);
989
+ }
990
+ function readRedirect(reader) {
991
+ const uriLength = reader.readVarint();
992
+ const connectUri = utf8Decode(reader.readBytes(uriLength));
993
+ const trackNamespace = readTrackNamespace(reader);
994
+ const nameLength = reader.readVarint();
995
+ const trackName = utf8Decode(reader.readBytes(nameLength));
996
+ return { connectUri, trackNamespace, trackName };
997
+ }
998
+ /**
999
+ * Decode one control-message frame into a typed message. Throws `MoqtProtocolError` for unknown message types (§9: "An
1000
+ * endpoint that receives an unknown message type MUST close the session") and for malformed bodies.
1001
+ */
1002
+ export function decodeControlMessage(frame, protocol = MOQT_PROTOCOL_ID) {
1003
+ const reader = new ByteReader(frame.body);
1004
+ const end = frame.body.length;
1005
+ let message;
1006
+ try {
1007
+ message = decodeControlMessageBody(frame.type, reader, end, protocol);
1008
+ }
1009
+ catch (error) {
1010
+ // Field reads past the declared frame length surface as `RangeError`
1011
+ // from `ByteReader`. Normalize them: the session's stream loops treat
1012
+ // only `MoqtProtocolError` as fatal, and a truncated body must
1013
+ // terminate the session (§9) rather than vanish as a read error.
1014
+ if (error instanceof RangeError) {
1015
+ throw new MoqtProtocolError(`control message 0x${frame.type.toString(16)} body is truncated`);
1016
+ }
1017
+ throw error;
1018
+ }
1019
+ if (reader.offset !== end) {
1020
+ throw new MoqtProtocolError(`control message 0x${frame.type.toString(16)} body length mismatch`);
1021
+ }
1022
+ return message;
1023
+ }
1024
+ function decodeControlMessageBody(type, reader, end, protocol) {
1025
+ switch (type) {
1026
+ case MESSAGE_TYPE.SETUP:
1027
+ return { kind: 'setup', options: decodeKeyValuePairs(reader, end) };
1028
+ case MESSAGE_TYPE.GOAWAY: {
1029
+ const uriLength = reader.readVarint();
1030
+ if (uriLength > MAX_NEW_SESSION_URI_LENGTH) {
1031
+ throw new MoqtProtocolError('GOAWAY new session URI exceeds 8192 bytes');
1032
+ }
1033
+ const newSessionUri = utf8Decode(reader.readBytes(uriLength));
1034
+ return { kind: 'goaway', newSessionUri, timeout: reader.readVarint() };
1035
+ }
1036
+ case MESSAGE_TYPE.SUBSCRIBE_OK: {
1037
+ const trackAlias = reader.readVarint();
1038
+ const parameters = decodeMessageParameters(reader, protocol);
1039
+ return { kind: 'subscribe-ok', trackAlias, parameters, trackProperties: decodeKeyValuePairs(reader, end) };
1040
+ }
1041
+ case MESSAGE_TYPE.REQUEST_OK: {
1042
+ const parameters = decodeMessageParameters(reader, protocol);
1043
+ return { kind: 'request-ok', parameters, trackProperties: decodeKeyValuePairs(reader, end) };
1044
+ }
1045
+ case MESSAGE_TYPE.REQUEST_ERROR: {
1046
+ const errorCode = reader.readVarint();
1047
+ const retryInterval = reader.readVarint();
1048
+ const reason = readReasonPhrase(reader);
1049
+ if (errorCode === REQUEST_ERROR_CODE.REDIRECT) {
1050
+ return { kind: 'request-error', errorCode, retryInterval, reason, redirect: readRedirect(reader) };
1051
+ }
1052
+ return { kind: 'request-error', errorCode, retryInterval, reason };
1053
+ }
1054
+ case MESSAGE_TYPE.REQUEST_UPDATE: {
1055
+ const requestId = reader.readVarint();
1056
+ return { kind: 'request-update', requestId, parameters: decodeMessageParameters(reader, protocol) };
1057
+ }
1058
+ case MESSAGE_TYPE.PUBLISH_STATE_NOTIFY:
1059
+ return { kind: 'publish-state-notify', parameters: decodeMessageParameters(reader, protocol) };
1060
+ case MESSAGE_TYPE.PUBLISH_DONE: {
1061
+ const statusCode = reader.readVarint();
1062
+ // A publisher that cannot count its streams MUST send 2^64−1 (§9.9),
1063
+ // which is above this codec's varint ceiling — read that one value as
1064
+ // "unknown" rather than failing the session over a legitimate
1065
+ // PUBLISH_DONE. Any other count past the ceiling stays a protocol error.
1066
+ const streamCount = reader.readCountVarint();
1067
+ return { kind: 'publish-done', statusCode, streamCount, reason: readReasonPhrase(reader) };
1068
+ }
1069
+ case MESSAGE_TYPE.PUBLISH: {
1070
+ const requestId = reader.readVarint();
1071
+ const trackNamespace = readTrackNamespace(reader);
1072
+ const trackName = utf8Decode(reader.readBytes(reader.readVarint()));
1073
+ const trackAlias = reader.readVarint();
1074
+ const parameters = decodeMessageParameters(reader, protocol);
1075
+ return {
1076
+ kind: 'publish',
1077
+ requestId,
1078
+ trackNamespace,
1079
+ trackName,
1080
+ trackAlias,
1081
+ parameters,
1082
+ trackProperties: decodeKeyValuePairs(reader, end),
1083
+ };
1084
+ }
1085
+ case MESSAGE_TYPE.PUBLISH_NAMESPACE: {
1086
+ const requestId = reader.readVarint();
1087
+ const trackNamespace = readTrackNamespace(reader);
1088
+ return {
1089
+ kind: 'publish-namespace',
1090
+ requestId,
1091
+ trackNamespace,
1092
+ parameters: decodeMessageParameters(reader, protocol),
1093
+ };
1094
+ }
1095
+ case MESSAGE_TYPE.FETCH_OK: {
1096
+ const endOfTrackWire = reader.readUint8();
1097
+ if (endOfTrackWire > 1)
1098
+ throw new MoqtProtocolError(`invalid FETCH_OK end-of-track value ${endOfTrackWire}`);
1099
+ const endOfTrack = endOfTrackWire === 1;
1100
+ const endLocation = readLocation(reader);
1101
+ const parameters = decodeMessageParameters(reader, protocol);
1102
+ return {
1103
+ kind: 'fetch-ok',
1104
+ endOfTrack,
1105
+ endLocation,
1106
+ parameters,
1107
+ trackProperties: decodeKeyValuePairs(reader, end),
1108
+ };
1109
+ }
1110
+ case MESSAGE_TYPE.SUBSCRIBE:
1111
+ case MESSAGE_TYPE.TRACK_STATUS:
1112
+ case MESSAGE_TYPE.FETCH: {
1113
+ const requestId = reader.readVarint();
1114
+ const trackNamespace = readTrackNamespace(reader);
1115
+ const trackName = utf8Decode(reader.readBytes(reader.readVarint()));
1116
+ const parameters = decodeMessageParameters(reader, protocol);
1117
+ if (type === MESSAGE_TYPE.FETCH) {
1118
+ return { kind: 'fetch', request: { requestId, trackNamespace, trackName, parameters } };
1119
+ }
1120
+ const kind = type === MESSAGE_TYPE.SUBSCRIBE ? 'subscribe' : 'track-status';
1121
+ return { kind, requestId, trackNamespace, trackName, parameters };
1122
+ }
1123
+ case MESSAGE_TYPE.SUBSCRIBE_NAMESPACE: {
1124
+ const requestId = reader.readVarint();
1125
+ const trackNamespacePrefix = readTrackNamespace(reader);
1126
+ return {
1127
+ kind: 'subscribe-namespace',
1128
+ requestId,
1129
+ trackNamespacePrefix,
1130
+ parameters: decodeMessageParameters(reader, protocol),
1131
+ };
1132
+ }
1133
+ case MESSAGE_TYPE.NAMESPACE:
1134
+ return { kind: 'namespace', trackNamespaceSuffix: readTrackNamespace(reader) };
1135
+ case MESSAGE_TYPE.NAMESPACE_DONE:
1136
+ return { kind: 'namespace-done', trackNamespaceSuffix: readTrackNamespace(reader) };
1137
+ case MESSAGE_TYPE.PUBLISH_SKIPPED: {
1138
+ const trackNamespaceSuffix = readTrackNamespace(reader);
1139
+ const trackName = utf8Decode(reader.readBytes(reader.readVarint()));
1140
+ return { kind: 'publish-skipped', trackNamespaceSuffix, trackName };
1141
+ }
1142
+ default:
1143
+ throw new MoqtProtocolError(`unknown control message type 0x${type.toString(16)}`);
1144
+ }
1145
+ }
1146
+ //# sourceMappingURL=control-messages.js.map