@volter/world-core 3.0.151 → 3.0.153

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 (52) hide show
  1. package/dist/src/derived-core.d.ts +8 -0
  2. package/dist/src/derived-core.js +2 -0
  3. package/dist/src/derived.d.ts +4 -0
  4. package/dist/src/events.d.ts +4 -4
  5. package/dist/src/events.js +39 -15
  6. package/dist/src/index.d.ts +3 -1
  7. package/dist/src/index.js +2 -1
  8. package/dist/src/live/access.d.ts +22 -0
  9. package/dist/src/live/access.js +83 -0
  10. package/dist/src/live/amf0.d.ts +7 -0
  11. package/dist/src/live/amf0.js +122 -0
  12. package/dist/src/live/flv.d.ts +42 -0
  13. package/dist/src/live/flv.js +148 -0
  14. package/dist/src/live/fmp4.d.ts +25 -0
  15. package/dist/src/live/fmp4.js +96 -0
  16. package/dist/src/live/hls.d.ts +22 -0
  17. package/dist/src/live/hls.js +46 -0
  18. package/dist/src/live/index.d.ts +9 -0
  19. package/dist/src/live/index.js +8 -0
  20. package/dist/src/live/ingest.d.ts +25 -0
  21. package/dist/src/live/ingest.js +229 -0
  22. package/dist/src/live/rtmp.d.ts +35 -0
  23. package/dist/src/live/rtmp.js +456 -0
  24. package/dist/src/live/segmenter.d.ts +57 -0
  25. package/dist/src/live/segmenter.js +204 -0
  26. package/dist/src/live/types.d.ts +102 -0
  27. package/dist/src/live/types.js +5 -0
  28. package/dist/src/pack-fetch.d.ts +4 -0
  29. package/dist/src/pack-fetch.js +24 -2
  30. package/dist/src/packRegistry.d.ts +1 -0
  31. package/dist/src/serve-http.d.ts +7 -1
  32. package/dist/src/serve-http.js +36 -3
  33. package/dist/src/twin-fetch.d.ts +4 -1
  34. package/package.json +5 -1
  35. package/src/derived-core.ts +10 -0
  36. package/src/derived.ts +4 -0
  37. package/src/events.ts +40 -16
  38. package/src/index.ts +4 -1
  39. package/src/live/access.ts +89 -0
  40. package/src/live/amf0.ts +80 -0
  41. package/src/live/flv.ts +145 -0
  42. package/src/live/fmp4.ts +102 -0
  43. package/src/live/hls.ts +59 -0
  44. package/src/live/index.ts +13 -0
  45. package/src/live/ingest.ts +210 -0
  46. package/src/live/rtmp.ts +375 -0
  47. package/src/live/segmenter.ts +218 -0
  48. package/src/live/types.ts +105 -0
  49. package/src/pack-fetch.ts +28 -2
  50. package/src/packRegistry.ts +1 -1
  51. package/src/serve-http.ts +29 -4
  52. package/src/twin-fetch.ts +4 -2
@@ -2,6 +2,7 @@ import { type TwinResource } from './serve.js';
2
2
  import { GitObjectStore } from './git/objects.js';
3
3
  import { GitRefs } from './git/refs.js';
4
4
  import { type SocketDecl, type SocketSession } from './sockets.js';
5
+ import type { LiveAccess, LiveDecl } from './live/types.js';
5
6
  import { type MachinePool } from './machines.js';
6
7
  import { type ApplicationAnswer, type ApplicationStandIn, type EventRender, type EventScheme, type EventsDecl, type EventValues } from './events.js';
7
8
  import type { RateBudgetDeclaration } from './rateBudget.js';
@@ -766,6 +767,10 @@ export type DerivedManifest = {
766
767
  /** The persistent wires the vendor's clients hold open (sockets.ts: Discord's Gateway): each served at its path by
767
768
  * the pack's `semantics/sockets.ts`, which the kernel offers every write after its webhooks. */
768
769
  sockets?: ReadonlyArray<SocketDecl>;
770
+ /** The broadcasts the vendor takes over RTMP (architecture, "Other wires": live media): each ingest's id, which names
771
+ * its engine in the pack's `semantics/live.ts`, and the RTMP app it answers. The pack's fetch carries the ingest
772
+ * (`fetch.ingest`), which its server serves on a side port. */
773
+ live?: ReadonlyArray<LiveDecl>;
769
774
  /** The vendor speaks gRPC (architecture, "Other wires": gRPC): its server answers HTTP/2 and HTTP/1 on one port, each
770
775
  * rpc (by its proto unit's schema, `src/generated/proto.gen.json`) through the pack's own fetch. */
771
776
  grpc?: true;
@@ -949,6 +954,9 @@ export type SemanticsContext = {
949
954
  issue(resource: string): Promise<string>;
950
955
  /** The vendor's open sessions of one of its sockets in this World (a request answered by a session: sockets.ts). */
951
956
  sockets(id: string): SocketSession[];
957
+ /** The World's recordings of what was broadcast to this twin (live media, live/access.ts): a recording's facts, and its
958
+ * playlists, init and segments answered as the vendor's media host answers them. */
959
+ live: LiveAccess;
952
960
  /** Hold this read until the World writes (held-reads.ts: HTTP long polling): true when a write of one of the named
953
961
  * resources lands in this World, false when `ms` pass or the client hangs up; at once false in a read-only World. */
954
962
  awaitWrite(resources: ReadonlyArray<string>, ms: number): Promise<boolean>;
@@ -15,6 +15,7 @@ import { GitRefs } from "./git/refs.js";
15
15
  import { worldNow } from "./world-clock.js";
16
16
  import { worldEnvValue } from "./world-env.js";
17
17
  import { openSessions, socketWrite } from "./sockets.js";
18
+ import { liveAccess } from "./live/access.js";
18
19
  import { awaitWrite, awaitCondition, heldReadsWrite } from "./held-reads.js";
19
20
  import { MACHINE_POOL, poolFor, guardedMachinePool } from "./machines.js";
20
21
  import { askApplication, deliverEvents } from "./events.js";
@@ -1538,6 +1539,7 @@ export async function contextFor(m, call, scope) {
1538
1539
  ...(options.database === undefined ? {} : { database: options.database }),
1539
1540
  ...(options.transaction === undefined ? {} : { transaction: options.transaction }),
1540
1541
  }),
1542
+ live: liveAccess({ rows: (type) => resourcesOfType(m.service, type, root), blob: (key) => readResourceBlob(m.service, key, root) }, call.request),
1541
1543
  blobs: {
1542
1544
  put: (key, bytes) => writeResourceBlob(m.service, key, bytes, root),
1543
1545
  get: (key) => readResourceBlob(m.service, key, root),
@@ -1,4 +1,5 @@
1
1
  import type { WebSocketUpgrade } from './serve-http.js';
2
+ import type { TwinStream } from './twin-fetch.js';
2
3
  /** The slice of a generated surface the dispatch reads. */
3
4
  export type DerivedOperation = {
4
5
  id: string;
@@ -126,6 +127,9 @@ export type DerivedFetch = ((request: Request) => Promise<Response>) & {
126
127
  ownersByUnit?(): Record<string, Record<string, DerivedOwner>>;
127
128
  /** The vendor's sockets (sockets.ts), for the serve seam to upgrade to, when its manifest declares any. */
128
129
  upgrade?: WebSocketUpgrade;
130
+ /** The vendor's RTMP ingest (live/ingest.ts), for its server to serve on its side port (`serveStream`), when its
131
+ * manifest declares `live`. */
132
+ ingest?: TwinStream;
129
133
  maxRequestBodySize?: number;
130
134
  /** The workspace screens it draws, its lanes' too (`GET /twin`'s `screens`). */
131
135
  workspaces?(): Workspace[];
@@ -140,11 +140,11 @@ export type EventDelivery = {
140
140
  /** The transport a delivery is made over; the World's by default, a test's own when given. */
141
141
  export type EventTransport = (url: string, body: string, headers: Record<string, string>) => Promise<number | void>;
142
142
  /** A signature scheme's headers for one delivery: deterministic (the id is derived from the delivery itself). */
143
- /** `seq` tells apart two identical deliveries at one instant (a frozen World clock): the World's count of deliveries
144
- * made before this one, so a receiver that deduplicates by id drops neither. */
145
- export declare function signEvent(scheme: EventScheme, secret: string, body: string, seconds: number, url: string, seq?: number): Record<string, string>;
143
+ /** `seq` tells apart deliveries at one instant; the declared-event path reserves it durably. `identity` supplies that
144
+ * occurrence's namespace. Omitted, existing direct callers retain their deterministic signing contract. */
145
+ export declare function signEvent(scheme: EventScheme, secret: string, body: string, seconds: number, url: string, seq?: number, identity?: string): Record<string, string>;
146
146
  /** Every scheme's headers for one delivery, merged. */
147
- export declare function signEventAll(schemes: EventScheme | ReadonlyArray<EventScheme>, secret: string, body: string, seconds: number, url: string, seq?: number): Record<string, string>;
147
+ export declare function signEventAll(schemes: EventScheme | ReadonlyArray<EventScheme>, secret: string, body: string, seconds: number, url: string, seq?: number, identity?: string): Record<string, string>;
148
148
  /** A delivery's signature checked as its receiver checks it (a Standard Webhooks verifier, a timestamp-v1 verifier, a plain
149
149
  * HMAC header): true when one of its signatures is the one the secret makes (constant time), and its timestamp,
150
150
  * when the scheme sends one, is within `tolerance` seconds of `now`. */
@@ -7,7 +7,7 @@
7
7
  // Imports stay free of side effects: the delivery's transport (Node's http, the World's egress policy) is loaded when a
8
8
  // delivery is made, never when a browser client imports the kernel.
9
9
  import { createHash, createHmac } from 'node:crypto';
10
- import { applyTwinWrite, twinResources } from "./serve.js";
10
+ import { applyTwinWrite, applyTwinWriteAtomic, twinResources } from "./serve.js";
11
11
  import { equalSecrets as same, ksuidFrom } from "./signing.js";
12
12
  import { deliveryTraceHeaders } from "./trace-context.js";
13
13
  /** Whether an endpoint takes an event by its `match`: every field of one match (any, when several) equal to the event's
@@ -25,16 +25,15 @@ function matches(row, match, filled) {
25
25
  });
26
26
  return Array.isArray(match) ? match.some(one) : one(match);
27
27
  }
28
- const digest = (s) => createHash('sha256').update(s).digest('hex');
29
28
  /** A `webhook-id` scheme's key: the base64 part of the secret, after its prefix when it carries one. */
30
29
  const webhookKey = (scheme, secret) => scheme.secretKey === 'utf8' ? Buffer.from(secret, 'utf8') : Buffer.from(scheme.secretPrefix && secret.startsWith(scheme.secretPrefix) ? secret.slice(scheme.secretPrefix.length) : secret, 'base64');
31
30
  /** A signature scheme's headers for one delivery: deterministic (the id is derived from the delivery itself). */
32
- /** `seq` tells apart two identical deliveries at one instant (a frozen World clock): the World's count of deliveries
33
- * made before this one, so a receiver that deduplicates by id drops neither. */
34
- export function signEvent(scheme, secret, body, seconds, url, seq = 0) {
31
+ /** `seq` tells apart deliveries at one instant; the declared-event path reserves it durably. `identity` supplies that
32
+ * occurrence's namespace. Omitted, existing direct callers retain their deterministic signing contract. */
33
+ export function signEvent(scheme, secret, body, seconds, url, seq = 0, identity) {
35
34
  if (scheme.kind === 'webhook-id') {
36
35
  // Svix's `msg_` and a KSUID (its ids' form), derived from the delivery itself
37
- const id = `msg_${ksuidFrom(seconds, seq, `${url}|${seconds}|${seq}|${body}`)}`;
36
+ const id = `msg_${ksuidFrom(seconds, seq, identity ?? `${url}|${seconds}|${seq}|${body}`)}`;
38
37
  const p = scheme.prefix.toLowerCase();
39
38
  const signature = createHmac('sha256', webhookKey(scheme, secret)).update(`${id}.${seconds}.${body}`, 'utf8').digest('base64');
40
39
  return { [`${p}-id`]: id, [`${p}-timestamp`]: String(seconds), [`${p}-signature`]: `v1,${signature}` };
@@ -58,8 +57,24 @@ const hashOf = (scheme, secret, body) => {
58
57
  /** What an `hmac` scheme signs: its `signed` template, else `${t}.${body}` with a timestamp header, else the body. */
59
58
  const hmacBase = (scheme, seconds, body) => scheme.signed !== undefined ? scheme.signed.replaceAll('{t}', String(seconds)).replaceAll('{body}', body) : scheme.timestampHeader ? `${seconds}.${body}` : body;
60
59
  /** Every scheme's headers for one delivery, merged. */
61
- export function signEventAll(schemes, secret, body, seconds, url, seq = 0) {
62
- return Object.assign({}, ...(Array.isArray(schemes) ? schemes : [schemes]).map((scheme) => signEvent(scheme, secret, body, seconds, url, seq)));
60
+ export function signEventAll(schemes, secret, body, seconds, url, seq = 0, identity) {
61
+ return Object.assign({}, ...(Array.isArray(schemes) ? schemes : [schemes]).map((scheme) => signEvent(scheme, secret, body, seconds, url, seq, identity)));
62
+ }
63
+ /** Reserve occurrences under the same cross-process lock that appends actions. This private retained row is never a
64
+ * vendor resource. Deleted event/delivery rows, concurrent renders and restarts cannot give its ordinals back. */
65
+ async function reserveEventOrdinals(service, root, occurredAt, count) {
66
+ const { value } = await applyTwinWriteAtomic(service, (resources) => {
67
+ const counter = resources.find((r) => r.type === '_world_event_sequence' && r.id === 'sequence');
68
+ const last = counter === undefined ? 0 : counter.last_ordinal;
69
+ if (typeof last !== 'number' || !Number.isSafeInteger(last) || last < 0 || !Number.isSafeInteger(count) || count < 1 || !Number.isSafeInteger(last + count)) {
70
+ throw new Error('Invalid retained declared-event sequence; occurrence ids cannot be reused.');
71
+ }
72
+ return { kind: 'write', value: last + 1, write: {
73
+ operation: 'world_event_sequence.reserve', subjectType: '_world_event_sequence', subjectId: 'sequence',
74
+ fields: { last_ordinal: last + count }, input: { clock: true }, occurredAt, actor: { kind: 'system' },
75
+ } };
76
+ }, root);
77
+ return value;
63
78
  }
64
79
  /** A delivery's signature checked as its receiver checks it (a Standard Webhooks verifier, a timestamp-v1 verifier, a plain
65
80
  * HMAC header): true when one of its signatures is the one the secret makes (constant time), and its timestamp,
@@ -282,11 +297,19 @@ async function deliverEventType(service, decl, write, data, transport, values, t
282
297
  const seconds = Math.floor(millis / 1000);
283
298
  const eventData = await data(type);
284
299
  const extra = values ? await values(type) : {};
285
- // the World's count of events kept so far tells apart two identical events at one instant (a frozen clock)
286
- const kept = decl.store !== undefined ? all.filter((r) => r.type === decl.store).length : 0;
300
+ // Reserve one event and at most one delivery per live endpoint before assigning identities. Unused ordinals are
301
+ // harmless gaps; a failed render/store never gives them back. This is not an atomic originating-write outbox.
302
+ const ordinal = await reserveEventOrdinals(service, write.root, write.occurredAt, 1 + live.length);
303
+ // Fresh/forked Worlds can reserve the same ordinal at a pinned clock. Keep
304
+ // content binding as well as the lineage's occurrence ordinal, so different
305
+ // event payloads cannot reuse a receiver's event/webhook id across those Worlds.
306
+ const eventContent = createHash('sha256').update(JSON.stringify({
307
+ operation: write.operation, type, data: eventData, envelope: decl.envelope,
308
+ values: extra, request: requestValues(write.request),
309
+ }), 'utf8').digest('hex');
287
310
  const filled = {
288
311
  $type: type, $data: eventData,
289
- $id: `evt_${ksuidFrom(seconds, kept, `${type}|${write.occurredAt}|${kept}|${JSON.stringify(eventData)}`)}`,
312
+ $id: `evt_${ksuidFrom(seconds, ordinal, `world-events:v1:${service}:${type}:${ordinal}:${eventContent}`)}`,
290
313
  '$time.ms': millis, '$time.s': seconds, '$time.iso': write.occurredAt,
291
314
  ...requestValues(write.request),
292
315
  ...extra,
@@ -305,18 +328,19 @@ async function deliverEventType(service, decl, write, data, transport, values, t
305
328
  const shared = JSON.stringify(envelope);
306
329
  const each = perEndpoint(decl.envelope);
307
330
  const sent = [];
308
- const before = decl.record !== undefined ? all.filter((r) => r.type === decl.record).length : 0;
309
331
  for (const [i, { row, kind }] of endpoints.entries()) {
310
332
  const body = each ? JSON.stringify(fillEnvelope(decl.envelope, filled, row)) : shared;
311
333
  const url = String(at(row, kind.url));
312
- const seq = before + i;
334
+ const seq = ordinal + 1 + i;
335
+ const deliveryContent = createHash('sha256').update(url, 'utf8').update('\0').update(body, 'utf8').digest('hex');
336
+ const identity = `world-events:v1:${service}:${seq}:${deliveryContent}`;
313
337
  const extraHeaders = decl.headers ? headersFor(decl.headers, filled, row) : {};
314
- const headers = { ...extraHeaders, ...signEventAll(decl.scheme, String(at(row, kind.secret)), body, seconds, url, seq) };
338
+ const headers = { ...extraHeaders, ...signEventAll(decl.scheme, String(at(row, kind.secret)), body, seconds, url, seq, identity) };
315
339
  sent.push({ url, body, headers });
316
340
  // kept with the write, by an id of the delivery itself (two made at once never take the same one)
317
341
  if (decl.record !== undefined) {
318
342
  await applyTwinWrite(service, {
319
- operation: `${decl.record.slice(1)}.record`, subjectType: decl.record, subjectId: `${decl.record.slice(1)}_${digest(`${url}|${seconds}|${seq}|${body}`).slice(0, 16)}`,
343
+ operation: `${decl.record.slice(1)}.record`, subjectType: decl.record, subjectId: `${decl.record.slice(1)}_v1_${seq}`,
320
344
  fields: { url, body, headers, event_type: type, sent_at: millis }, occurredAt: write.occurredAt, actor: { kind: 'system' },
321
345
  }, write.root);
322
346
  }
@@ -25,6 +25,7 @@ export { verifyEvent } from './events.js';
25
25
  export { deriveStateSystem, deriveVendorStateSystem } from './derived-real.js';
26
26
  export type { IngestDecl } from './derived-core.js';
27
27
  export type { SocketDecl, SocketEngine, SocketSession } from './sockets.js';
28
+ export type { LiveAccess, LiveAdmission, LiveAudio, LiveDecl, LiveEngine, LivePublish, LiveRecording, LiveRefusal, LiveServeOptions, LiveVideo } from './live/types.js';
28
29
  export { machinePool, isMachineCapabilityGap, type ExecSpec, type MachinePool, type MachineProcess, type MachineRun, type MachineSpec, type MachineStatus, type MachineFiles, type MachineFileStat } from './machines.js';
29
30
  export type { CorsDecl } from './cors.js';
30
31
  export type { Handler, HandlerContext, WriteHookContext } from './derived-core.js';
@@ -39,7 +40,7 @@ export { answerVendorErrors, RefusedWriteError } from './head.js';
39
40
  export { GraphqlError, type GraphqlPart, type GraphqlResolver } from './graphql-wire.js';
40
41
  export { VendorUnreachableError } from './vendor-call.js';
41
42
  export { isReadOnlyRequest, READ_ONLY_REQUEST_HEADER } from './request-scope.js';
42
- export { serveHttp, serveStream, type HttpHandler, type HttpServer, type ServeHttpOptions } from './serve-http.js';
43
+ export { serveHttp, serveStream, StreamListenerUnavailable, type HttpHandler, type HttpServer, type ServeHttpOptions } from './serve-http.js';
43
44
  export type { TwinStream, TwinStreamConnection, TwinStreamSink } from './twin-fetch.js';
44
45
  export { privateTransportKey } from './private-transport.js';
45
46
  export { siteLabel, siteUrlOf, twinSiteUrl, twinVendorUrl } from './twin-fetch.js';
@@ -68,6 +69,7 @@ export { placeholderPng } from './placeholder-image.js';
68
69
  export { presignSigV4, signSigV4, verifySigV4, type SigV4Verdict } from './sigv4.js';
69
70
  export * as redis from './redis/index.js';
70
71
  export * as mysql from './mysql/index.js';
72
+ export * as live from './live/index.js';
71
73
  export * as git from './git/index.js';
72
74
  export { parseScenarioDocument, scenarioFaultResult, ScenarioEngine, ScenarioError } from './scenario.js';
73
75
  export type { PackScenarioAdapter, ScenarioDecision, ScenarioDocument, ScenarioExtractorSpec, ScenarioFault, ScenarioFaultResult, ScenarioFeatures, ScenarioHandler, ScenarioMatcher, ScenarioMissRecord, ScenarioStatus } from './scenario.js';
package/dist/src/index.js CHANGED
@@ -29,7 +29,7 @@ export { GraphqlError } from "./graphql-wire.js";
29
29
  export { VendorUnreachableError } from "./vendor-call.js";
30
30
  export { isReadOnlyRequest, READ_ONLY_REQUEST_HEADER } from "./request-scope.js";
31
31
  // ── the serve factory ──────────────────────────────────────────────────────────────────────────
32
- export { serveHttp, serveStream } from "./serve-http.js";
32
+ export { serveHttp, serveStream, StreamListenerUnavailable } from "./serve-http.js";
33
33
  export { privateTransportKey } from "./private-transport.js";
34
34
  // where a page links a hostname its twin answers, inside the World that shows it
35
35
  export { siteLabel, siteUrlOf, twinSiteUrl, twinVendorUrl } from "./twin-fetch.js";
@@ -60,6 +60,7 @@ export { placeholderPng } from "./placeholder-image.js";
60
60
  export { presignSigV4, signSigV4, verifySigV4 } from "./sigv4.js";
61
61
  export * as redis from "./redis/index.js";
62
62
  export * as mysql from "./mysql/index.js";
63
+ export * as live from "./live/index.js";
63
64
  export * as git from "./git/index.js";
64
65
  // ── the scenario grammar (architecture, "Behaviour") ───────────────────────────────────────────
65
66
  export { parseScenarioDocument, scenarioFaultResult, ScenarioEngine, ScenarioError } from "./scenario.js";
@@ -0,0 +1,22 @@
1
+ import { type HlsSegment } from './hls.js';
2
+ import type { LiveAccess, LiveRecording } from './types.js';
3
+ /** The bookkeeping types a recording is kept in. */
4
+ export declare const LIVE = "_live";
5
+ export declare const LIVE_SEGMENT = "_live_segment";
6
+ /** Where a recording's bytes are kept among the pack's resource blobs. */
7
+ export declare const initBlob: (stream: string, init: number) => string;
8
+ export declare const segmentBlob: (stream: string, seq: number) => string;
9
+ type Row = Record<string, unknown>;
10
+ export type LiveReads = {
11
+ rows(type: string): Row[];
12
+ blob(key: string): Promise<Uint8Array | null>;
13
+ };
14
+ /** A recording's kept segments, in order. */
15
+ export declare function segmentsOf(reads: LiveReads, stream: string): Array<HlsSegment & {
16
+ start: number;
17
+ blob: string;
18
+ }>;
19
+ export declare function recordingOf(row: Row, segments: ReadonlyArray<HlsSegment>): LiveRecording;
20
+ /** `ctx.live` over a request (the one a media host answers, for its Range and its method). */
21
+ export declare function liveAccess(reads: LiveReads, request: Request): LiveAccess;
22
+ export {};
@@ -0,0 +1,83 @@
1
+ // What a handler and a screen read of the World's recordings (`ctx.live`, architecture "Other wires": live media): a
2
+ // recording's facts from its bookkeeping subjects, and its playlists, init and segments answered as a media host
3
+ // answers them. The recording's rows are the tree's (`_live`, `_live_segment`); the bytes are the pack's resource blobs.
4
+ import { bytesResponse } from "../file-response.js";
5
+ import { masterPlaylist, mediaPlaylist } from "./hls.js";
6
+ /** The bookkeeping types a recording is kept in. */
7
+ export const LIVE = '_live';
8
+ export const LIVE_SEGMENT = '_live_segment';
9
+ /** Where a recording's bytes are kept among the pack's resource blobs. */
10
+ export const initBlob = (stream, init) => `live/${stream}/init-${init}.mp4`;
11
+ export const segmentBlob = (stream, seq) => `live/${stream}/seg-${seq}.m4s`;
12
+ /** A recording's kept segments, in order. */
13
+ export function segmentsOf(reads, stream) {
14
+ return reads.rows(LIVE_SEGMENT)
15
+ .filter((r) => r.stream === stream && r.deleted !== true)
16
+ .map((r) => ({ seq: Number(r.seq), init: Number(r.init), duration: Number(r.duration), size: Number(r.size), start: Number(r.start), blob: String(r.blob) }))
17
+ .sort((a, b) => a.seq - b.seq);
18
+ }
19
+ export function recordingOf(row, segments) {
20
+ return {
21
+ stream: String(row.id),
22
+ app: String(row.app ?? ''),
23
+ key: String(row.key ?? ''),
24
+ state: row.state === 'ended' ? 'ended' : 'publishing',
25
+ startedAt: String(row.startedAt ?? ''),
26
+ ...(typeof row.endedAt === 'string' ? { endedAt: row.endedAt } : {}),
27
+ publishes: Number(row.publishes ?? 1),
28
+ segments: segments.length,
29
+ duration: Math.round(segments.reduce((n, s) => n + s.duration, 0) * 1000) / 1000,
30
+ ...(row.video && typeof row.video === 'object' ? { video: row.video } : {}),
31
+ ...(row.audio && typeof row.audio === 'object' ? { audio: row.audio } : {}),
32
+ ...(row.metadata && typeof row.metadata === 'object' ? { metadata: row.metadata } : {}),
33
+ };
34
+ }
35
+ const CORS = { 'access-control-allow-origin': '*' };
36
+ const missing = () => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8', ...CORS } });
37
+ /** `ctx.live` over a request (the one a media host answers, for its Range and its method). */
38
+ export function liveAccess(reads, request) {
39
+ const rowOf = (stream) => reads.rows(LIVE).find((r) => r.id === stream && r.deleted !== true);
40
+ return {
41
+ recording(stream) {
42
+ const row = rowOf(stream);
43
+ return row ? recordingOf(row, segmentsOf(reads, stream)) : undefined;
44
+ },
45
+ recordings() {
46
+ return reads.rows(LIVE).filter((r) => r.deleted !== true).map((r) => recordingOf(r, segmentsOf(reads, String(r.id))));
47
+ },
48
+ async serve(stream, file, options = {}) {
49
+ const row = rowOf(stream);
50
+ if (!row)
51
+ return missing();
52
+ const segments = segmentsOf(reads, stream);
53
+ const ended = row.state === 'ended';
54
+ if (file === 'index.m3u8' || file === 'master.m3u8') {
55
+ // a recording with nothing playable yet has no playlist: a player waits, as for a stream not yet live
56
+ if (!segments.length)
57
+ return missing();
58
+ const recording = recordingOf(row, segments);
59
+ const uri = options.uri ?? ((f) => f);
60
+ const text = file === 'index.m3u8'
61
+ ? mediaPlaylist({ state: recording.state, ...(typeof row.window === 'number' ? { window: row.window } : {}) }, segments, options)
62
+ : masterPlaylist(recording, segments, uri('index.m3u8'));
63
+ return new Response(request.method === 'HEAD' ? null : text, { headers: { 'content-type': 'application/vnd.apple.mpegurl', 'cache-control': ended ? 'public, max-age=3600' : 'no-cache, no-store', ...CORS } });
64
+ }
65
+ const init = /^init-(\d{1,9})\.mp4$/.exec(file);
66
+ const seg = /^seg-(\d{1,12})\.m4s$/.exec(file);
67
+ let key;
68
+ if (init && segments.some((s) => s.init === Number(init[1])))
69
+ key = initBlob(stream, Number(init[1]));
70
+ else if (seg)
71
+ key = segments.find((s) => s.seq === Number(seg[1]))?.blob;
72
+ if (!key)
73
+ return missing();
74
+ const bytes = await reads.blob(key);
75
+ if (!bytes)
76
+ return missing();
77
+ const answer = bytesResponse(request, bytes, 'video/mp4');
78
+ for (const [k, v] of Object.entries(CORS))
79
+ answer.headers.set(k, v);
80
+ return answer;
81
+ },
82
+ };
83
+ }
@@ -0,0 +1,7 @@
1
+ export type Amf0Value = number | boolean | string | null | undefined | Date | Amf0Value[] | {
2
+ [key: string]: Amf0Value;
3
+ };
4
+ /** Every value in `bytes`, in order; a value of a type AMF0 commands do not carry ends the read. */
5
+ export declare function decodeAmf0(bytes: Uint8Array): Amf0Value[];
6
+ /** `values` as AMF0, in order. */
7
+ export declare function encodeAmf0(...values: Amf0Value[]): Uint8Array;
@@ -0,0 +1,122 @@
1
+ // AMF0, the encoding of RTMP's commands and data messages (Adobe's AMF0 specification, as RTMP 1.0 §7 uses it): a
2
+ // command is a sequence of values (its name, a transaction id, an object, its arguments). Read: number, boolean,
3
+ // string, object, null, undefined, ECMA array, strict array, date, long string, typed object; a reference (0x07) is read
4
+ // as undefined, never followed, so no value read is cyclic (a publisher's metadata pointing back at itself); anything
5
+ // else stops the read where it is. Written: number, boolean, string, object (and a plain record), null, undefined.
6
+ const utf8 = new TextDecoder();
7
+ const encoder = new TextEncoder();
8
+ /** Every value in `bytes`, in order; a value of a type AMF0 commands do not carry ends the read. */
9
+ export function decodeAmf0(bytes) {
10
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11
+ let at = 0;
12
+ const str = (length) => { const s = utf8.decode(bytes.subarray(at, at + length)); at += length; return s; };
13
+ const key = () => { const n = view.getUint16(at); at += 2; return str(n); };
14
+ const properties = (into) => {
15
+ for (;;) {
16
+ if (at + 3 > bytes.length)
17
+ return into;
18
+ if (view.getUint16(at) === 0 && bytes[at + 2] === 0x09) {
19
+ at += 3;
20
+ return into;
21
+ }
22
+ const name = key();
23
+ into[name] = value();
24
+ }
25
+ };
26
+ const value = () => {
27
+ const marker = bytes[at++];
28
+ switch (marker) {
29
+ case 0x00: {
30
+ const n = view.getFloat64(at);
31
+ at += 8;
32
+ return n;
33
+ }
34
+ case 0x01: return bytes[at++] !== 0;
35
+ case 0x02: return key();
36
+ case 0x03: return properties({});
37
+ case 0x05: return null;
38
+ case 0x06: return undefined;
39
+ case 0x07:
40
+ at += 2;
41
+ return undefined;
42
+ case 0x08:
43
+ at += 4;
44
+ return properties({});
45
+ case 0x0a: {
46
+ const n = view.getUint32(at);
47
+ at += 4;
48
+ const list = [];
49
+ for (let i = 0; i < n && at < bytes.length; i++)
50
+ list.push(value());
51
+ return list;
52
+ }
53
+ case 0x0b: {
54
+ const ms = view.getFloat64(at);
55
+ at += 10;
56
+ return new Date(ms);
57
+ }
58
+ case 0x0c: {
59
+ const n = view.getUint32(at);
60
+ at += 4;
61
+ return str(n);
62
+ }
63
+ case 0x10:
64
+ key();
65
+ return properties({});
66
+ default: throw new Amf0End();
67
+ }
68
+ };
69
+ const out = [];
70
+ while (at < bytes.length) {
71
+ try {
72
+ out.push(value());
73
+ }
74
+ catch (error) {
75
+ if (error instanceof Amf0End || error instanceof RangeError)
76
+ break;
77
+ throw error;
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+ class Amf0End extends Error {
83
+ }
84
+ /** `values` as AMF0, in order. */
85
+ export function encodeAmf0(...values) {
86
+ const parts = [];
87
+ const u16 = (n) => { parts.push((n >> 8) & 0xff, n & 0xff); };
88
+ const text = (s) => { const b = encoder.encode(s); u16(b.length); for (const x of b)
89
+ parts.push(x); };
90
+ const write = (v) => {
91
+ if (typeof v === 'number') {
92
+ parts.push(0x00);
93
+ const b = new Uint8Array(8);
94
+ new DataView(b.buffer).setFloat64(0, v);
95
+ for (const x of b)
96
+ parts.push(x);
97
+ }
98
+ else if (typeof v === 'boolean')
99
+ parts.push(0x01, v ? 1 : 0);
100
+ else if (typeof v === 'string') {
101
+ parts.push(0x02);
102
+ text(v);
103
+ }
104
+ else if (v === null)
105
+ parts.push(0x05);
106
+ else if (v === undefined)
107
+ parts.push(0x06);
108
+ else if (v instanceof Date || Array.isArray(v))
109
+ throw new Error('amf0: this writer writes no dates or arrays');
110
+ else {
111
+ parts.push(0x03);
112
+ for (const [k, x] of Object.entries(v)) {
113
+ text(k);
114
+ write(x);
115
+ }
116
+ parts.push(0x00, 0x00, 0x09);
117
+ }
118
+ };
119
+ for (const v of values)
120
+ write(v);
121
+ return Uint8Array.from(parts);
122
+ }
@@ -0,0 +1,42 @@
1
+ export type AvcConfig = {
2
+ /** the AVCDecoderConfigurationRecord as sent, which an `avcC` box holds as is (ISO/IEC 14496-15 §5.3.3.1) */
3
+ record: Uint8Array;
4
+ /** the RFC 6381 codec string: `avc1.` and the profile, constraint flags and level, in hex */
5
+ codec: string;
6
+ width: number;
7
+ height: number;
8
+ };
9
+ export type AacConfig = {
10
+ /** the AudioSpecificConfig as sent, which an `esds` box's DecoderSpecificInfo holds as is */
11
+ asc: Uint8Array;
12
+ codec: string;
13
+ objectType: number;
14
+ sampleRate: number;
15
+ channels: number;
16
+ };
17
+ export type VideoTag = {
18
+ kind: 'config';
19
+ config: AvcConfig;
20
+ } | {
21
+ kind: 'frame';
22
+ key: boolean;
23
+ cts: number;
24
+ data: Uint8Array;
25
+ } | {
26
+ kind: 'other';
27
+ } | {
28
+ kind: 'unsupported';
29
+ codec: string;
30
+ };
31
+ export type AudioTag = {
32
+ kind: 'config';
33
+ config: AacConfig;
34
+ } | {
35
+ kind: 'frame';
36
+ data: Uint8Array;
37
+ } | {
38
+ kind: 'unsupported';
39
+ codec: string;
40
+ };
41
+ export declare function readVideoTag(p: Uint8Array): VideoTag;
42
+ export declare function readAudioTag(p: Uint8Array): AudioTag;