@blockcast/mmt-container 2.2.0-main.cc3fe0684403 → 2.2.0-main.d79fbb738dc0

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 (126) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-creative-record.d.ts +65 -0
  7. package/dist/ad-creative-record.d.ts.map +1 -0
  8. package/dist/ad-creative-record.js +2281 -0
  9. package/dist/ad-creative-record.js.map +7 -0
  10. package/dist/ad-creative-timeline.d.ts +102 -0
  11. package/dist/ad-creative-timeline.d.ts.map +1 -0
  12. package/dist/ad-creative-timeline.js +2529 -0
  13. package/dist/ad-creative-timeline.js.map +7 -0
  14. package/dist/block-policy.d.ts +128 -14
  15. package/dist/block-policy.d.ts.map +1 -1
  16. package/dist/block-policy.js +472 -27
  17. package/dist/block-policy.js.map +2 -2
  18. package/dist/browser-runtime.js +1040 -120
  19. package/dist/browser-runtime.js.map +4 -4
  20. package/dist/carp-catalog.d.ts +1 -0
  21. package/dist/carp-catalog.d.ts.map +1 -1
  22. package/dist/carp-catalog.js +34 -0
  23. package/dist/carp-catalog.js.map +4 -4
  24. package/dist/catalog-fec-params.js.map +1 -1
  25. package/dist/catalog-network-source.d.ts +1 -17
  26. package/dist/catalog-network-source.d.ts.map +1 -1
  27. package/dist/catalog-network-source.js +25 -19
  28. package/dist/catalog-network-source.js.map +3 -3
  29. package/dist/cmaf-block-assembler.d.ts +10 -2
  30. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  31. package/dist/cmaf-block-assembler.js +30 -8
  32. package/dist/cmaf-block-assembler.js.map +3 -3
  33. package/dist/codec-utils.d.ts.map +1 -1
  34. package/dist/codec-utils.js +16 -3
  35. package/dist/codec-utils.js.map +2 -2
  36. package/dist/conceal-timeline.d.ts +24 -1
  37. package/dist/conceal-timeline.d.ts.map +1 -1
  38. package/dist/conceal-timeline.js +201 -4
  39. package/dist/conceal-timeline.js.map +3 -3
  40. package/dist/datagram-leg-deadline.d.ts +26 -2
  41. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  42. package/dist/datagram-leg-deadline.js +14 -2
  43. package/dist/datagram-leg-deadline.js.map +2 -2
  44. package/dist/event-timeline-mmtp.d.ts +17 -0
  45. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  46. package/dist/event-timeline-mmtp.js +3117 -0
  47. package/dist/event-timeline-mmtp.js.map +7 -0
  48. package/dist/fec-manager.d.ts +24 -3
  49. package/dist/fec-manager.d.ts.map +1 -1
  50. package/dist/fec-manager.js +531 -38
  51. package/dist/fec-manager.js.map +2 -2
  52. package/dist/feed-gate.d.ts +114 -0
  53. package/dist/feed-gate.d.ts.map +1 -0
  54. package/dist/feed-gate.js +175 -0
  55. package/dist/feed-gate.js.map +7 -0
  56. package/dist/index.d.ts +4 -3
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +16 -2
  59. package/dist/index.js.map +2 -2
  60. package/dist/iso-bmff-timing.d.ts +16 -0
  61. package/dist/iso-bmff-timing.d.ts.map +1 -1
  62. package/dist/iso-bmff-timing.js +28 -0
  63. package/dist/iso-bmff-timing.js.map +2 -2
  64. package/dist/mfu-reassembler.d.ts +2 -0
  65. package/dist/mfu-reassembler.d.ts.map +1 -1
  66. package/dist/mfu-reassembler.js +4 -2
  67. package/dist/mfu-reassembler.js.map +2 -2
  68. package/dist/mmtp-container-parser.d.ts +12 -0
  69. package/dist/mmtp-container-parser.d.ts.map +1 -1
  70. package/dist/mmtp-container-parser.js +73 -3
  71. package/dist/mmtp-container-parser.js.map +2 -2
  72. package/dist/mmtp-container-parser.no-modules.js +103 -25
  73. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  74. package/dist/mmtp-decode-pipeline.js +73 -3
  75. package/dist/mmtp-decode-pipeline.js.map +2 -2
  76. package/dist/mmtp-router.d.ts +20 -2
  77. package/dist/mmtp-router.d.ts.map +1 -1
  78. package/dist/mmtp-router.js +150 -23
  79. package/dist/mmtp-router.js.map +3 -3
  80. package/dist/multicast-auth-catalog.js.map +1 -1
  81. package/dist/multicast-input.js.map +1 -1
  82. package/dist/multicast-manager.d.ts +23 -2
  83. package/dist/multicast-manager.d.ts.map +1 -1
  84. package/dist/multicast-manager.js +737 -86
  85. package/dist/multicast-manager.js.map +3 -3
  86. package/dist/multicast-transport.js +44 -22
  87. package/dist/multicast-transport.js.map +2 -2
  88. package/dist/no-modules.js +98 -22
  89. package/dist/no-modules.js.map +4 -4
  90. package/dist/repair-fetch.d.ts +15 -7
  91. package/dist/repair-fetch.d.ts.map +1 -1
  92. package/dist/repair-fetch.js +34 -7
  93. package/dist/repair-fetch.js.map +2 -2
  94. package/dist/wasm-mfu-reassembler.js.map +2 -2
  95. package/dist/wasm-mmtp-container-parser.js +73 -3
  96. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  97. package/package.json +17 -5
  98. package/schemas/catalog.schema.json +7 -2
  99. package/src/ad-creative-record.ts +276 -0
  100. package/src/ad-creative-timeline.ts +409 -0
  101. package/src/block-policy.ts +673 -42
  102. package/src/carp-catalog.ts +9 -0
  103. package/src/catalog-network-source.ts +3 -37
  104. package/src/cmaf-block-assembler.ts +17 -0
  105. package/src/codec-utils.ts +19 -3
  106. package/src/conceal-timeline.ts +60 -5
  107. package/src/datagram-leg-deadline.ts +34 -2
  108. package/src/event-timeline-mmtp.ts +55 -0
  109. package/src/fec-manager.ts +84 -12
  110. package/src/feed-gate.ts +295 -0
  111. package/src/index.ts +22 -0
  112. package/src/iso-bmff-timing.ts +33 -0
  113. package/src/mfu-reassembler.ts +4 -0
  114. package/src/mmtp-container-parser.ts +51 -5
  115. package/src/mmtp-router.ts +116 -4
  116. package/src/multicast-manager.ts +31 -0
  117. package/src/repair-fetch.ts +70 -19
  118. package/test-vectors/catalog/README.md +1 -0
  119. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  120. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  121. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  122. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  123. package/test-vectors/catalog/section-codes.json +1 -0
  124. package/test-vectors/catalog-timing.json +184 -1
  125. package/test-vectors/frame-needs-v1.json +295 -0
  126. package/test-vectors/repair-policy-v1.json +98 -18
@@ -0,0 +1,409 @@
1
+ /**
2
+ * The ad creative timeline (draft-riedl-moq-ad-creative-signaling-01): verified records placed on
3
+ * the depends track's media time (riedl 5.1, 5.4) and fired at most once from the player's
4
+ * presented time (riedl 11). No clock and no I/O. Imports ad-creative-record (noble): subpath only.
5
+ */
6
+ import { serial32Distance, serial32Precedes } from '@blockcast/mmt-base'
7
+ import {
8
+ canonicalJson, parseAdCreativeObject,
9
+ type AdCreativeKeys, type AdCreativeRecord, type AdIndex, type AdObjectDrop, type AdRecordDrop,
10
+ } from './ad-creative-record.js'
11
+
12
+ export * from './ad-creative-record.js'
13
+
14
+ export interface AdScheduledEvent {
15
+ /** Unique within a record: container key, tracking type and its occurrence. */
16
+ readonly eventKey: string
17
+ /** The slot's key (riedl 10 item 8: identifiers plus occurrence), or null for a pod or record event. */
18
+ readonly slotKey: string | null
19
+ readonly eventType: string
20
+ readonly urls: readonly string[]
21
+ readonly dueMs: number
22
+ /** podStart only: the pod's end, so a joiner inside the pod still fires it (riedl 11). Absent when the pod has no duration. */
23
+ readonly podEndMs?: number
24
+ }
25
+
26
+ export interface AdSlotWindow {
27
+ readonly slotKey: string
28
+ readonly startMs: number
29
+ }
30
+
31
+ export interface AdSchedule {
32
+ /** Sorted by dueMs; among equal times podStart first and podEnd last. */
33
+ readonly events: readonly AdScheduledEvent[]
34
+ readonly slots: readonly AdSlotWindow[]
35
+ }
36
+
37
+ /**
38
+ * Time-driven tracking types without an `offset`, as a fraction of the container's duration
39
+ * (VAST 4.2 semantics; SVTA 2053-1 4.4.5 not read). Only these and `progress`, which needs an
40
+ * explicit `offset` (VAST 4.2), are scheduled. Interaction and error types (pause, skip,
41
+ * clickTracking, error) belong to the player, offset or not: fired from a shared schedule, a whole
42
+ * audience would report them.
43
+ */
44
+ const FRACTION = new Map<string, number>([
45
+ ['podStart', 0], ['impression', 0], ['start', 0], ['firstQuartile', 0.25],
46
+ ['midpoint', 0.5], ['thirdQuartile', 0.75], ['complete', 1], ['podEnd', 1],
47
+ ])
48
+ const TIMED: ReadonlySet<string> = new Set([...FRACTION.keys(), 'progress'])
49
+ const rank = (type: string): number => (type === 'podStart' ? 0 : type === 'podEnd' ? 2 : 1)
50
+ /** SVTA MediaTime: seconds (riedl 4.3). */
51
+ const seconds = (value: unknown): number | undefined =>
52
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
53
+
54
+ function containerEvents(tracking: unknown, startMs: number, durationS: number | undefined, prefix: string, slotKey: string | null): AdScheduledEvent[] {
55
+ const events: AdScheduledEvent[] = []
56
+ const occurrences = new Map<string, number>()
57
+ for (const entry of Array.isArray(tracking) ? tracking : []) {
58
+ if (typeof entry !== 'object' || entry === null) continue
59
+ const event = entry as Record<string, unknown>
60
+ const type = event['type']
61
+ const urls = event['urls']
62
+ if (typeof type !== 'string' || !TIMED.has(type) || !Array.isArray(urls)) continue
63
+ const n = occurrences.get(type) ?? 0
64
+ occurrences.set(type, n + 1)
65
+ const fraction = FRACTION.get(type)
66
+ // A present but malformed offset drops the entry: it states a time, and the fraction default would fire at one nobody authored.
67
+ if (event['offset'] !== undefined && seconds(event['offset']) === undefined) continue
68
+ const atS = seconds(event['offset']) ??
69
+ (fraction === 0 ? 0 : fraction !== undefined && durationS !== undefined ? fraction * durationS : undefined)
70
+ if (atS === undefined) continue
71
+ events.push({
72
+ eventKey: `${prefix}|${type}#${n}`,
73
+ slotKey,
74
+ eventType: type,
75
+ urls: Object.freeze([...(urls as string[])]),
76
+ dueMs: startMs + Math.round(atS * 1000),
77
+ // A joiner fires podStart late only inside a pod of known length; without one it fires on time or not at all.
78
+ ...(type === 'podStart' && slotKey === null && durationS !== undefined
79
+ ? { podEndMs: startMs + Math.round(durationS * 1000) }
80
+ : {}),
81
+ })
82
+ }
83
+ return events
84
+ }
85
+
86
+ function slotEvents(slots: unknown, containerStartMs: number, prefix: string, events: AdScheduledEvent[], windows: AdSlotWindow[]): void {
87
+ const occurrences = new Map<string, number>()
88
+ for (const entry of Array.isArray(slots) ? slots : []) {
89
+ if (typeof entry !== 'object' || entry === null) continue
90
+ const slot = entry as Record<string, unknown>
91
+ // riedl 10 item 8: a slot's key is its identifiers plus how many earlier slots carry the same ones.
92
+ const ids = canonicalJson(slot['identifiers'] ?? null)
93
+ const n = occurrences.get(ids) ?? 0
94
+ occurrences.set(ids, n + 1)
95
+ const slotKey = `${prefix}/${ids}#${n}`
96
+ const startMs = containerStartMs + Math.round((seconds(slot['start']) ?? 0) * 1000)
97
+ windows.push({ slotKey, startMs })
98
+ events.push(...containerEvents(slot['tracking'], startMs, seconds(slot['duration']), slotKey, slotKey))
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Place a record's events. `startMs` is the record index on the depends track's media time (for
104
+ * `m`, the index itself; riedl 5.1). Interior times are seconds relative to their container
105
+ * (riedl 4.3, 5.4); in a slot or trackingEvent envelope the record index stands in for the Pod.
106
+ */
107
+ export function scheduleAdRecord(record: AdCreativeRecord, startMs: number): AdSchedule {
108
+ const events: AdScheduledEvent[] = []
109
+ const slots: AdSlotWindow[] = []
110
+ const { type, payload } = record.data
111
+ if (type === 'pod') {
112
+ payload.forEach((pod, i) => {
113
+ // A pod with a non-zero start never gets here: parseAdCreativeRecord ignores it as 'timing' (Question 13).
114
+ events.push(...containerEvents(pod['tracking'], startMs, seconds(pod['duration']), `pod${i}`, null))
115
+ slotEvents(pod['slots'], startMs, `pod${i}`, events, slots)
116
+ })
117
+ }
118
+ if (type === 'slot') slotEvents(payload, startMs, 'slot', events, slots)
119
+ if (type === 'trackingEvent') events.push(...containerEvents(payload, startMs, undefined, 'record', null))
120
+ // 'verification' schedules nothing: the verified record event hands it to the player (riedl 12.3).
121
+ events.sort((a, b) => a.dueMs - b.dueMs || rank(a.eventType) - rank(b.eventType))
122
+ return { events, slots }
123
+ }
124
+
125
+ /** Where an Object came from: its MoQ Location, or on multicast its MPU sequence number and Item_ID. */
126
+ export interface AdObjectLocation {
127
+ readonly groupId: number
128
+ readonly objectId: number
129
+ }
130
+
131
+ export type AdTimelineEvent =
132
+ | {
133
+ readonly type: 'record'
134
+ readonly status: 'added' | 'superseded' | 'removed'
135
+ readonly key: string
136
+ readonly verified: true
137
+ /** Only a verified record's contents ever leave the timeline (riedl 4.5). */
138
+ readonly record: AdCreativeRecord
139
+ }
140
+ /** observeUnverified only: an unverified record's key, never its contents (riedl 4.5: it is absent). */
141
+ | { readonly type: 'record'; readonly status: 'added' | 'superseded' | 'removed'; readonly key: string; readonly verified: false }
142
+ | {
143
+ readonly type: 'rejected'
144
+ readonly reason: AdObjectDrop | AdRecordDrop | 'unmappable' | 'stale-group' | 'replayed'
145
+ readonly key?: string
146
+ readonly location: AdObjectLocation
147
+ }
148
+ | {
149
+ readonly type: 'track'
150
+ readonly key: string
151
+ readonly slotKey: string | null
152
+ readonly eventType: string
153
+ readonly urls: readonly string[]
154
+ readonly dueMs: number
155
+ readonly mediaTimeMs: number
156
+ }
157
+ | {
158
+ /** observeUnverified only: an event of an unsigned or unknown-key record. It carries no URL. */
159
+ readonly type: 'observed'
160
+ readonly key: string
161
+ readonly slotKey: string | null
162
+ readonly eventType: string
163
+ readonly dueMs: number
164
+ readonly mediaTimeMs: number
165
+ }
166
+ export type AdTrackEvent = Extract<AdTimelineEvent, { type: 'track' }>
167
+ export type AdTimelineObserver = (event: AdTimelineEvent) => void
168
+
169
+ export interface AdCreativeTimelineOptions {
170
+ /** The channel's key set (importAdCreativeJwks with the channel's kids). */
171
+ keys: AdCreativeKeys
172
+ /** Media ms of a t or l index on the depends track's timeline, or null. Default: only m maps (riedl 4.2). */
173
+ mapIndex?: (index: AdIndex) => number | null
174
+ /** An event due longer ago than this is skipped, never burst; a forward jump this long is a seek. Default 2000. */
175
+ maxLateMs?: number
176
+ /** Schedule unsigned and unknown-key records as 'observed' events, which carry no URL (live interop). Default false. */
177
+ observeUnverified?: boolean
178
+ }
179
+
180
+ interface Entry {
181
+ record: AdCreativeRecord
182
+ schedule: AdSchedule
183
+ verified: boolean
184
+ /** Events fired or skipped: at most once per (index, slot, type) (riedl 10 item 3). Kept across verified supersedes. */
185
+ readonly done: Set<string>
186
+ /** Canonical forms of the verified versions this index replaced: a re-served one is 'replayed' (riedl 12.1). */
187
+ readonly replaced: Set<string>
188
+ joined: boolean
189
+ /** The latest end over every verified version this index held, so a tombstone outlives each one it can refuse. */
190
+ endMs: number
191
+ }
192
+
193
+ /** What a removed verified index leaves behind, so a re-add can neither replay nor re-fire (riedl 12.1, 10 item 3). */
194
+ interface Tombstone {
195
+ readonly done: Set<string>
196
+ readonly replaced: Set<string>
197
+ readonly endMs: number
198
+ /** Dropped once the presented time passes this: endMs plus maxLateMs. */
199
+ readonly untilMs: number
200
+ /** Playback never stopped, so a restore keeps the join; a seek clears it. */
201
+ joined: boolean
202
+ }
203
+
204
+ /** Where a version stops mattering: its last event, or its index for a record with none. */
205
+ const versionEndMs = (schedule: AdSchedule, startMs: number) =>
206
+ Math.max(startMs, ...schedule.events.map((e) => e.podEndMs ?? e.dueMs))
207
+
208
+ /** A late Group up to this many behind is stale; one further away in either direction is a new epoch (about 50 min of ~3 s Groups). */
209
+ const EPOCH_GROUPS = 1024
210
+ const utf8 = new TextDecoder()
211
+
212
+ /**
213
+ * Takes Object payloads only. The MSF_EVENT_TIMELINE_HEADER track property (msf-02 8.1, 0x7B) is
214
+ * the subscriber's to read: riedl -01 defines no header, so a present one is a diagnostic there and
215
+ * never a reason to accept a record the signature check drops. It assumes the msf-02 8.4 sequence mapping
216
+ * (Object 0 holds every accessible record, later Objects add); under the "independent of its history"
217
+ * mapping every Group's Object 0 would remove the previous Group's records.
218
+ */
219
+ export class AdCreativeTimeline {
220
+ /** Replace to rotate keys (riedl 4.5); a verified record stays until an independent Object drops it. */
221
+ keys: AdCreativeKeys
222
+ readonly #mapIndex: (index: AdIndex) => number | null
223
+ readonly #maxLateMs: number
224
+ readonly #observeUnverified: boolean
225
+ readonly #observers = new Set<AdTimelineObserver>()
226
+ readonly #entries = new Map<string, Entry>()
227
+ readonly #tombstones = new Map<string, Tombstone>()
228
+ /** This Group's Objects already applied, by objectId: the payloads seen, so only an identical copy is skipped. */
229
+ readonly #objects = new Map<number, Set<string>>()
230
+ #group: number | undefined
231
+ #lastMs: number | undefined
232
+
233
+ constructor(options: AdCreativeTimelineOptions) {
234
+ this.keys = options.keys
235
+ this.#mapIndex = options.mapIndex ?? ((index) => (index.kind === 'm' ? index.ms : null))
236
+ this.#maxLateMs = options.maxLateMs ?? 2000
237
+ this.#observeUnverified = options.observeUnverified ?? false
238
+ }
239
+
240
+ addObserver(observer: AdTimelineObserver): () => void {
241
+ this.#observers.add(observer)
242
+ return () => {
243
+ this.#observers.delete(observer)
244
+ }
245
+ }
246
+
247
+ /** One Object of the track, from MoQ or from the multicast data path (EventTimelineMmtpReader). */
248
+ ingest(bytes: Uint8Array, location: AdObjectLocation): void {
249
+ // Multicast carries the Group ID mod 2^32: both legs compare in that space (RFC 1982). A Group further than
250
+ // EPOCH_GROUPS away replaces the set even where RFC 1982 calls it older: a publisher restart (msf-02 6.1,
251
+ // unchanged from msf-01 6.1; a wallclock-ms first Group, riedl 11), or an injected Group, whose damage then
252
+ // lasts one heartbeat.
253
+ const group = location.groupId >>> 0
254
+ if (this.#group !== undefined && serial32Precedes(group, this.#group) && serial32Distance(group, this.#group) <= EPOCH_GROUPS) {
255
+ this.#emit({ type: 'rejected', reason: 'stale-group', location })
256
+ return
257
+ }
258
+ // The other leg's copy, or a redelivery. Compare content, not location: a corrupted or injected copy that
259
+ // arrives first must not mask the authentic one.
260
+ const payload = utf8.decode(bytes)
261
+ if (group === this.#group && this.#objects.get(location.objectId)?.has(payload)) return
262
+ const result = parseAdCreativeObject(bytes, this.keys)
263
+ if (result.verdict !== 'accepted') {
264
+ this.#emit({ type: 'rejected', reason: result.verdict, location })
265
+ return
266
+ }
267
+ if (group !== this.#group) {
268
+ this.#group = group
269
+ this.#objects.clear()
270
+ }
271
+ // riedl -01 inherits msf-01 8.3, which msf-02 8.4 keeps as its sequence case: Object 0 is independent and
272
+ // replaces the set; later Objects only add. An Object 0 that arrives after a later Object of its Group adds
273
+ // too, or it would drop that Object's records.
274
+ const replace = location.objectId === 0 && [...this.#objects.keys()].every((id) => id === 0)
275
+ const seen = this.#objects.get(location.objectId) ?? new Set<string>()
276
+ this.#objects.set(location.objectId, seen.add(payload))
277
+ const present = new Set<string>()
278
+ // A record whose signature fails or is malformed means this copy was altered after signing, so it is not the
279
+ // publisher's Object 0 and removes nothing: the next heartbeat's Object 0 does (riedl 11). Policy drops an honest
280
+ // publisher can send (feature, timing, an unknown key during rotation) still sweep; a relay can sweep with [] anyway.
281
+ let intact = true
282
+ for (const parsed of result.records) {
283
+ const verified = parsed.verdict === 'verified'
284
+ if (parsed.verdict === 'signature' || parsed.verdict === 'sig') intact = false
285
+ if (!verified) this.#emit({ type: 'rejected', reason: parsed.verdict as AdRecordDrop, key: parsed.key, location })
286
+ const record = parsed.record
287
+ // riedl 4.5: an unverified record is absent. Observe-only keeps unsigned and unknown-key ones, never their URLs.
288
+ if (!record || (!verified && !this.#observeUnverified)) continue
289
+ const startMs = this.#mapIndex(record.index)
290
+ if (startMs === null) {
291
+ this.#emit({ type: 'rejected', reason: 'unmappable', key: record.key, location })
292
+ continue
293
+ }
294
+ present.add(record.key)
295
+ const entry = this.#entries.get(record.key)
296
+ if (entry && entry.verified && !verified) continue // an unverified copy never displaces a verified record
297
+ if (entry && entry.verified === verified && entry.record.canonical === record.canonical) continue // heartbeat (riedl 11)
298
+ // riedl 12.1: a relay can re-serve, in a newer Group, a version a supersede replaced. Never go back to one.
299
+ // A removed index keeps its replaced versions as a tombstone, so remove-then-re-add cannot replay either.
300
+ const tombstone = this.#tombstones.get(record.key)
301
+ if (verified && (entry?.verified ? entry.replaced : tombstone?.replaced)?.has(record.canonical)) {
302
+ this.#emit({ type: 'rejected', reason: 'replayed', key: record.key, location })
303
+ continue
304
+ }
305
+ const schedule = scheduleAdRecord(record, startMs)
306
+ const endMs = versionEndMs(schedule, startMs)
307
+ // riedl 10 item 2: last writer wins at an index; fired events stay fired.
308
+ if (entry) {
309
+ if (entry.verified) entry.replaced.add(entry.record.canonical)
310
+ if (!entry.verified && verified) {
311
+ // Observed fires sent nothing, so the verified copy starts its events afresh (with the late-join rule),
312
+ // except those a removed verified version of this index already fired.
313
+ entry.done.clear()
314
+ for (const done of tombstone?.done ?? []) entry.done.add(done)
315
+ for (const version of tombstone?.replaced ?? []) entry.replaced.add(version)
316
+ entry.endMs = tombstone?.endMs ?? -Infinity
317
+ this.#tombstones.delete(record.key)
318
+ entry.joined = false
319
+ }
320
+ entry.endMs = verified ? Math.max(entry.endMs, endMs) : endMs
321
+ entry.record = record
322
+ entry.schedule = schedule
323
+ entry.verified = verified
324
+ } else {
325
+ const fromTombstone = verified ? tombstone : undefined
326
+ if (fromTombstone) this.#tombstones.delete(record.key)
327
+ this.#entries.set(record.key, {
328
+ record, schedule, verified, joined: fromTombstone?.joined ?? false,
329
+ endMs: Math.max(endMs, fromTombstone?.endMs ?? -Infinity),
330
+ done: new Set(fromTombstone?.done), replaced: new Set(fromTombstone?.replaced),
331
+ })
332
+ }
333
+ this.#emitRecord(entry ? 'superseded' : 'added', record, verified)
334
+ }
335
+ if (!replace || !intact) return
336
+ for (const [key, entry] of this.#entries) {
337
+ if (present.has(key)) continue
338
+ this.#entries.delete(key)
339
+ if (entry.verified) {
340
+ const { done, replaced, endMs, joined } = entry
341
+ this.#tombstones.set(key, { done, replaced, endMs, joined, untilMs: endMs + this.#maxLateMs })
342
+ }
343
+ this.#emitRecord('removed', entry.record, entry.verified)
344
+ }
345
+ }
346
+
347
+ /** Drive with the media time being presented, in ms on the depends track's timeline (riedl 5.1, 11). */
348
+ advance(mediaTimeMs: number): void {
349
+ // A forward jump past maxLateMs is a seek: re-join there instead of bursting what it crossed.
350
+ if (this.#lastMs !== undefined && mediaTimeMs - this.#lastMs > this.#maxLateMs) {
351
+ for (const entry of this.#entries.values()) entry.joined = false
352
+ for (const tombstone of this.#tombstones.values()) tombstone.joined = false
353
+ }
354
+ this.#lastMs = mediaTimeMs
355
+ for (const [key, tombstone] of this.#tombstones) if (tombstone.untilMs < mediaTimeMs) this.#tombstones.delete(key)
356
+ for (const [key, entry] of this.#entries) {
357
+ if (!entry.joined) this.#join(key, entry, mediaTimeMs)
358
+ for (const event of entry.schedule.events) {
359
+ if (entry.done.has(event.eventKey) || event.dueMs > mediaTimeMs) continue
360
+ entry.done.add(event.eventKey)
361
+ // Due longer ago than maxLateMs: a supersede moved it behind the playhead. Skip it.
362
+ if (mediaTimeMs - event.dueMs <= this.#maxLateMs) this.#fire(key, entry, event, mediaTimeMs)
363
+ }
364
+ }
365
+ }
366
+
367
+ // riedl 11 joiner policy: podStart on joining, nothing for a slot already in progress, full chains after it.
368
+ #join(key: string, entry: Entry, t: number): void {
369
+ entry.joined = true
370
+ for (const slot of entry.schedule.slots) {
371
+ if (t - slot.startMs <= this.#maxLateMs) continue
372
+ for (const event of entry.schedule.events) if (event.slotKey === slot.slotKey) entry.done.add(event.eventKey)
373
+ }
374
+ for (const event of entry.schedule.events) {
375
+ if (event.podEndMs === undefined || entry.done.has(event.eventKey) || event.dueMs > t || t >= event.podEndMs) continue
376
+ entry.done.add(event.eventKey)
377
+ this.#fire(key, entry, event, t)
378
+ }
379
+ }
380
+
381
+ #fire(key: string, entry: Entry, event: AdScheduledEvent, mediaTimeMs: number): void {
382
+ const { slotKey, eventType, dueMs } = event
383
+ if (entry.verified) {
384
+ this.#emit({ type: 'track', key, slotKey, eventType, urls: event.urls, dueMs, mediaTimeMs })
385
+ return
386
+ }
387
+ // An unverified slotKey would carry the record's identifiers (riedl 4.5: its contents are absent): an ordinal.
388
+ const ordinal = slotKey === null ? null : `slot#${entry.schedule.slots.findIndex((slot) => slot.slotKey === slotKey)}`
389
+ this.#emit({ type: 'observed', key, slotKey: ordinal, eventType, dueMs, mediaTimeMs })
390
+ }
391
+
392
+ // riedl 4.5: an unverified record is absent, so observe-only names its key and never its contents.
393
+ #emitRecord(status: 'added' | 'superseded' | 'removed', record: AdCreativeRecord, verified: boolean): void {
394
+ this.#emit(verified
395
+ ? { type: 'record', status, key: record.key, verified: true, record }
396
+ : { type: 'record', status, key: record.key, verified: false })
397
+ }
398
+
399
+ #emit(event: AdTimelineEvent): void {
400
+ Object.freeze(event)
401
+ for (const observer of this.#observers) {
402
+ try {
403
+ observer(event)
404
+ } catch (error) {
405
+ console.warn('[AdCreativeTimeline] observer failed', error)
406
+ }
407
+ }
408
+ }
409
+ }