rvlib-shipkit 2.10.0 → 2.12.0

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 (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +253 -0
  4. package/src/cli/cmd_Review.ts +4 -0
  5. package/src/cli/cmd_Trailer.ts +4 -0
  6. package/src/cli/family-pages.ts +1 -0
  7. package/src/cli/registry.ts +2 -0
  8. package/src/collections/pings.ts +6 -4
  9. package/src/core/app-icon.ts +17 -4
  10. package/src/core/scratch-objects.ts +56 -0
  11. package/src/core/trace-audit.ts +13 -1
  12. package/src/home/home-paths.ts +4 -0
  13. package/src/home/home-routes.ts +36 -2
  14. package/src/home/hubs.ts +5 -0
  15. package/src/home/inbox-shape.ts +188 -0
  16. package/src/home/inbox.ts +104 -0
  17. package/src/home/run-daemon.ts +12 -2
  18. package/src/home/serve-web.ts +161 -16
  19. package/src/ledger/git-scan.ts +73 -25
  20. package/src/ledger/repo-view.ts +2 -22
  21. package/src/media-kinds.ts +14 -0
  22. package/src/media-store/content.ts +61 -0
  23. package/src/media-store/daemon.ts +91 -0
  24. package/src/media-store/db.ts +74 -0
  25. package/src/media-store/fact.ts +9 -0
  26. package/src/media-store/hand.ts +58 -0
  27. package/src/media-store/kind.ts +44 -0
  28. package/src/media-store/purge.ts +139 -0
  29. package/src/media-store/put.ts +120 -0
  30. package/src/media-store/remote.ts +93 -0
  31. package/src/media-store/space.ts +167 -0
  32. package/src/media-store/sync.ts +101 -0
  33. package/src/media-store/upload.ts +98 -0
  34. package/src/repo-config.ts +4 -0
  35. package/src/review/anim.ts +6 -5
  36. package/src/review/cells.ts +5 -1
  37. package/src/review/media-kind.ts +84 -0
  38. package/src/review/media-read.ts +48 -0
  39. package/src/review/model.ts +22 -1
  40. package/src/review/previews.ts +41 -12
  41. package/src/review/routes.ts +32 -8
  42. package/src/review/store.ts +102 -40
  43. package/src/review/trailer-desk.ts +79 -46
  44. package/src/review/trailer-media.ts +181 -0
  45. package/src/review/trailer-routes.ts +5 -2
  46. package/src/review/trailer-shots.ts +89 -0
  47. package/src/serve/hub-app/cols-svc.ts +12 -1
  48. package/src/serve/hub-app/home-st.ts +39 -9
  49. package/src/serve/hub-app/home.html +2 -1
  50. package/src/serve/hub-app/hub-app.tsx +7 -23
  51. package/src/serve/hub-app/icons.tsx +2 -0
  52. package/src/serve/hub-app/inbox-st.ts +144 -0
  53. package/src/serve/hub-app/inbox-view.tsx +205 -0
  54. package/src/serve/hub-app/inbox.css +73 -0
  55. package/src/serve/hub-app/item-view.tsx +19 -0
  56. package/src/serve/hub-app/keys.ts +4 -3
  57. package/src/serve/hub-app/palette-st.ts +2 -1
  58. package/src/serve/hub-app/project-list.tsx +1 -0
  59. package/src/serve/hub-app/projects-svc.ts +1 -1
  60. package/src/serve/hub-app/repo-st.ts +1 -1
  61. package/src/serve/hub-app/review/review-st.ts +15 -3
  62. package/src/serve/hub-app/review/review-thread.tsx +5 -4
  63. package/src/serve/hub-app/review.css +1 -1
  64. package/src/serve/hub-app/test-view.tsx +9 -2
  65. package/src/serve/hub-app/tests-svc.ts +16 -1
  66. package/src/serve/hub-runtime.ts +9 -4
  67. package/src/serve/resources-wire.ts +48 -0
  68. package/src/serve/serve-hub.ts +11 -7
  69. package/src/serve/warm-cell.ts +6 -1
  70. package/src/trailer/footage.ts +6 -2
  71. package/src/trailer/passage.ts +8 -3
  72. package/src/trailer/prune.ts +6 -10
  73. package/src/trailer/shelf.ts +16 -0
@@ -8,6 +8,8 @@ import { basename, dirname, extname, join, resolve } from 'node:path'
8
8
  import { LAYOUT } from '../core/layout.ts'
9
9
  import { ffmpeg } from '../trailer/ffmpeg.ts'
10
10
  import { probe, sizeOf, stillAt } from './media.ts'
11
+ import { factsOf } from '../media-store/content.ts'
12
+ import { mediaDb, tryWrite } from '../media-store/db.ts'
11
13
  import {
12
14
  AGENT_RE,
13
15
  allowed,
@@ -47,6 +49,9 @@ import {
47
49
  type ReviewView,
48
50
  type Spec,
49
51
  type Subject,
52
+ viewFilesOf,
53
+ mediaFilesOf,
54
+ threadMediaOf,
50
55
  } from './model.ts'
51
56
  import { beatRole, roleOf } from './role.ts'
52
57
  import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
@@ -370,9 +375,10 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
370
375
  mkdirSync(tmp)
371
376
  loaded.forEach((v, n) => copyFiles(v, n, tmp))
372
377
  await Promise.all(loaded.map((v, n) => Promise.all([writePoster(v, n, tmp), writeWaves(v, n, tmp)])))
373
- writeJson(join(tmp, 'item.json'), item)
378
+ const head: Item = { ...item, media: await factsOf(tmp, viewFilesOf(item)) }
379
+ writeJson(join(tmp, 'item.json'), head)
374
380
  renameSync(tmp, join(dir, id))
375
- return item
381
+ return head
376
382
  }
377
383
 
378
384
  /** every file of view `n` into the folder, each as `<name>.tmp` renamed, so no reader sees half of one */
@@ -400,9 +406,41 @@ export async function addView(dir: string, id: string, v: ViewInput, o: { marks?
400
406
  copyFiles(loaded, n, folder)
401
407
  await writePoster(loaded, n, folder)
402
408
  await writeWaves(loaded, n, folder)
403
- const item: Item = { ...x.item, views: [...x.item.views, viewOf(loaded, n, o.marks, v.note)], ...(x.item.light || o.light ? { light: 'review' as const } : {}) }
404
- writeJson(join(folder, 'item.json'), item)
405
- return item
409
+ const view = viewOf(loaded, n, o.marks, v.note)
410
+ const facts = await factsOf(folder, viewFilesOf({ ...x.item, views: [view] }))
411
+ return updateHead(dir, id, (cur) => {
412
+ if (cur.views.length !== n) throw new Error(`${id}: another view landed while this one was written: add it again`)
413
+ return { ...cur, views: [...cur.views, view], media: { ...cur.media, ...facts }, ...(cur.light || o.light ? { light: 'review' as const } : {}) }
414
+ })
415
+ }
416
+
417
+ /** the head rewritten under the item's lock, from what the file says now: a write that raced this one is never lost */
418
+ export function updateHead(dir: string, id: string, fn: (cur: Item) => Item): Item {
419
+ return locked(dir, id, () => {
420
+ const f = join(dir, id, 'item.json')
421
+ const cur = JSON.parse(readFileSync(f, 'utf8')) as Item
422
+ const next = fn(cur)
423
+ const problems = itemProblems(next)
424
+ if (problems.length > 0) throw new Error(problems.join('; '))
425
+ writeJson(f, next)
426
+ return next
427
+ })
428
+ }
429
+
430
+ /** the media facts an item lacks (one written before facts were kept, a file whose size moved): each file still in the
431
+ * folder hashed, written under its lock; the item as it is when nothing was missing */
432
+ export async function fillMedia(dir: string, id: string): Promise<Item | null> {
433
+ const x = readRaw(dir, id)
434
+ if (!x) return null
435
+ const folder = join(dir, id)
436
+ const held = x.item.media ?? {}
437
+ const names = mediaFilesOf(x)
438
+ const size = (n: string): number | undefined => statSync(join(folder, n), { throwIfNoEntry: false })?.size
439
+ const stale = new Set(names.filter((n) => held[n] && size(n) !== undefined && size(n) !== held[n]?.size))
440
+ const lacks = names.filter((n) => !held[n] && existsSync(join(folder, n)))
441
+ if (lacks.length === 0 && stale.size === 0) return x.item
442
+ const facts = await factsOf(folder, [...lacks, ...stale], {}, stale)
443
+ return updateHead(dir, id, (cur) => ({ ...cur, media: { ...cur.media, ...facts } }))
406
444
  }
407
445
 
408
446
  export interface ReadAll {
@@ -509,19 +547,11 @@ function stampOf(folder: string): string {
509
547
  return `${one(folder)}:${one(`${folder}/thread`)}`
510
548
  }
511
549
 
512
- /** the index of a store: beside it, never inside it. Its own name, never `.review-index.json`: a second code that reads
513
- * the same store keys its index on its own code, and two codes sharing one file each throw the other's away */
514
- export const indexFile = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
515
-
516
550
  type Read = { x: ReviewItem } | { error: string }
517
551
 
518
- interface StoreIndex {
519
- /** the code that reads and checks an item: another code reads every item again */
520
- code: string
521
- items: Record<string, { stamp: string; read: Read }>
522
- }
523
-
524
552
  let codeKey: string | null = null
553
+ /** the code that reads and checks an item: the index keeps each code's reads apart, so two copies of the lib reading one
554
+ * store (the daemon's, a repo's own install) never throw each other's away */
525
555
  const indexCode = (): string => (codeKey ??= new Bun.CryptoHasher('sha1').update(readFileSync(import.meta.path)).update(readFileSync(join(import.meta.dir, 'model.ts'))).digest('hex'))
526
556
 
527
557
  function readOne(dir: string, id: string): Read {
@@ -554,39 +584,69 @@ function checked(raw: ReadAll, spec: Spec): ReadAll {
554
584
  return all
555
585
  }
556
586
 
557
- /** every item of the store, through its index: an item whose stamp moved is read again */
587
+ /** the json index each store kept beside it before the machine index, removed once per process */
588
+ const OLD_INDEX = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
589
+ const swept = new Set<string>()
590
+ /** the stores this process marked its code as using, once each */
591
+ const used = new Set<string>()
592
+ /** a code that read no store for this long: its reads go */
593
+ const CODE_KEEP_MS = 7 * 24 * 3600_000
594
+
595
+ /** every item of the store, through the machine index (space/db.ts): an item whose stamp moved is read again */
558
596
  function readRaws(dir: string): ReadAll {
559
597
  const out: ReadAll = { items: [], broken: [] }
560
598
  if (!existsSync(dir)) return out
561
- const file = indexFile(dir)
599
+ const store = resolve(dir)
562
600
  const code = indexCode()
563
- let was: StoreIndex['items'] = {}
564
- try {
565
- const ix = JSON.parse(readFileSync(file, 'utf8')) as StoreIndex
566
- if (ix.code === code) was = ix.items
567
- } catch {
568
- // no index yet, or one of another shape: read every item
601
+ const db = mediaDb()
602
+ const was = new Map<string, { stamp: string; read: string }>()
603
+ if (db)
604
+ try {
605
+ for (const r of db.query('select id, stamp, read from items where store = ? and code = ?').all(store, code) as { id: string; stamp: string; read: string }[]) was.set(r.id, r)
606
+ } catch (e) {
607
+ console.error(`WARN review index: ${store} read from its files: ${(e as Error).message}`)
608
+ }
609
+ if (!swept.has(store)) {
610
+ swept.add(store)
611
+ fs.rmSync(OLD_INDEX(dir), { force: true })
569
612
  }
570
- const next: StoreIndex = { code, items: {} }
571
- let moved = false
613
+ const moved: { id: string; stamp: string; read: Read }[] = []
614
+ const seen = new Set<string>()
572
615
  for (const id of readdirSync(dir).sort()) {
573
616
  if (id.startsWith('.')) continue
617
+ seen.add(id)
574
618
  const stamp = stampOf(join(dir, id))
575
- const held = was[id]
576
- const read = held && held.stamp === stamp ? held.read : readOne(dir, id)
577
- if (read !== held?.read) moved = true
578
- next.items[id] = { stamp, read }
619
+ const held = was.get(id)
620
+ let read: Read | null = null
621
+ if (held && held.stamp === stamp)
622
+ try {
623
+ read = JSON.parse(held.read) as Read
624
+ } catch {
625
+ read = null
626
+ }
627
+ if (!read) {
628
+ read = readOne(dir, id)
629
+ moved.push({ id, stamp, read })
630
+ }
579
631
  if ('x' in read) out.items.push(read.x)
580
632
  else out.broken.push({ id, error: read.error })
581
633
  }
582
- if (moved || Object.keys(was).length !== Object.keys(next.items).length)
583
- try {
584
- const tmp = `${file}.${process.pid}.tmp`
585
- fs.writeFileSync(tmp, JSON.stringify(next))
586
- fs.renameSync(tmp, file)
587
- } catch {
588
- // a read only store: the next read pays the whole read again
634
+ const gone = [...was.keys()].filter((id) => !seen.has(id))
635
+ const first = !used.has(store)
636
+ if (moved.length === 0 && gone.length === 0 && !first) return out
637
+ used.add(store)
638
+ tryWrite(`the reads of ${store}`, (d) => {
639
+ const now = Date.now()
640
+ d.query('insert or replace into codes (store, code, used) values (?, ?, ?)').run(store, code, now)
641
+ const put = d.query('insert or replace into items (store, code, id, stamp, read) values (?, ?, ?, ?, ?)')
642
+ for (const m of moved) put.run(store, code, m.id, m.stamp, JSON.stringify(m.read))
643
+ const drop = d.query('delete from items where store = ? and code = ? and id = ?')
644
+ for (const id of gone) drop.run(store, code, id)
645
+ for (const r of d.query('select code from codes where store = ? and used < ?').all(store, now - CODE_KEEP_MS) as { code: string }[]) {
646
+ d.query('delete from items where store = ? and code = ?').run(store, r.code)
647
+ d.query('delete from codes where store = ? and code = ?').run(store, r.code)
589
648
  }
649
+ })
590
650
  return out
591
651
  }
592
652
 
@@ -684,7 +744,7 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
684
744
  rmSync(tmp, { recursive: true, force: true })
685
745
  mkdirSync(tmp)
686
746
  if (input.image !== undefined && image) copyFileSync(input.image, join(tmp, image))
687
- writeJson(join(tmp, 'item.json'), item)
747
+ writeJson(join(tmp, 'item.json'), { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) })
688
748
  renameSync(tmp, join(dir, id))
689
749
  const who = input.origin.by === 'player' ? 'player' : 'owner'
690
750
  if (text) appendMessage(dir, id, { who, text, ...(input.rects && input.rects.length > 0 ? { rects: input.rects } : {}) }, { now })
@@ -877,8 +937,9 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
877
937
  views = [...views, viewOf(loaded, n)]
878
938
  }
879
939
  const next: Item = { ...r, views, wip: { live: r.wip.live, frame: r.wip.frame + 1 } }
880
- writeJson(join(folder, 'item.json'), next)
881
- return next
940
+ const fresh = new Set([image, ...views.flatMap((v) => ('gallery' in v ? v.gallery.map((g) => g.file) : []))])
941
+ const media = await factsOf(folder, [...viewFilesOf(next), ...threadMediaOf(r)], r.media, fresh)
942
+ return updateHead(dir, id, () => ({ ...next, media }))
882
943
  }
883
944
 
884
945
  /** the label of a draft card's history view */
@@ -902,8 +963,9 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
902
963
  const now = 'image' in files ? files.image : undefined
903
964
  if (old && old !== now) rmSync(join(folder, old), { force: true })
904
965
  item = { ...rest, views: [{ ...f0, files, size: loaded.size }, ...rest.views.slice(1)] }
966
+ item = { ...item, media: await factsOf(folder, [...viewFilesOf(item), ...threadMediaOf(rest)], rest.media, new Set(Object.values(files))) }
905
967
  }
906
- writeJson(join(dir, id, 'item.json'), item)
968
+ updateHead(dir, id, () => item)
907
969
  appendMessage(dir, id, { who: agentName(), op: 'ready' }, o.now ? { now: o.now } : {})
908
970
  return item
909
971
  }
@@ -2,9 +2,12 @@
2
2
  // is raised with: the note itself is an item of the one store, its subject the frame, anchored on its shot's name, so it
3
3
  // survives a new render of the cut. A cut is a `trailer/<id>/<cut>.trailer` and its render `out/<name>.mp4` (`<name>`
4
4
  // its `trailer` line), or a render with no file beside it. The trailer core (src/trailer/) is read, never changed
5
- import { constants, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
5
+ import { constants, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
6
6
  import { join, relative } from 'node:path'
7
7
  import { LAYOUT } from '../core/layout.ts'
8
+ import { mediaKey } from '../media-store/content.ts'
9
+ import type { MediaFact } from '../media-store/fact.ts'
10
+ import { fetchBack, signedUrl } from '../media-store/remote.ts'
8
11
  import { parseTrailer, starts, total, type Trailer } from '../trailer/grammar.ts'
9
12
  import { THUMB_W } from '../trailer/graph.ts'
10
13
  import { probe, stillAt } from './media.ts'
@@ -126,7 +129,7 @@ export function trailerIds(root: string): string[] {
126
129
  export const cutOf = (dir: string, cut: string): CutFiles | null => (CUT_RE.test(cut) ? (cutsOf(dir).find((c) => c.cut === cut) ?? null) : null)
127
130
  /** a cut's render: out/<name>.mp4, or a version's own */
128
131
  export const videoOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.mp4') ?? join(dir, 'versions', c.cut, `${c.cut}.mp4`)) : join(dir, 'out', `${c.name}.mp4`))
129
- const stripOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.strip.png') ?? join(dir, 'versions', c.cut, `${c.cut}.strip.png`)) : join(dir, 'out', `${c.name}.strip.png`))
132
+ export const stripOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.strip.png') ?? join(dir, 'versions', c.cut, `${c.cut}.strip.png`)) : join(dir, 'out', `${c.name}.strip.png`))
130
133
  export const montageOf = (dir: string, c: CutFiles): string => join(dir, 'out', `${c.name}.montage.md`)
131
134
 
132
135
  /** a cut's .trailer parsed: the film lines need the project CLI's words, which a timeline never does, so their errors
@@ -143,21 +146,32 @@ function parseCut(file: string): { trailer: Trailer; errors: string[] } {
143
146
  const SETTLE_MS = 2500
144
147
  const settled = (mtime: number, now: number): boolean => now - mtime > SETTLE_MS
145
148
 
146
- /** where each finished render is kept as the page plays it: an APFS clone, free, untouched by the next render */
149
+ /** where each finished render is recorded as the page plays it: its json, and an APFS clone of its video and strip
150
+ * (free, untouched by the next render) until the media store holds them (wiki build/trailer.md, Frame notes) */
147
151
  export const viewDir = (root: string): string => join(root, LAYOUT.cache, 'trailer-view')
148
- /** the versions kept per cut: the one on screen may be the one before the newest */
149
- const VIEWS_KEPT = 3
150
152
 
151
- /** a finished render of a cut: its clone, its length and rate, its size, the timeline it was rendered from (null: unknown) */
153
+ /** a render's files by their content, filled by the media store's scan (src/review/trailer-media.ts) */
154
+ export interface ViewMedia {
155
+ video?: MediaFact
156
+ strip?: MediaFact
157
+ /** the strip's width and height, so the timeline reads its grid once the clone is gone */
158
+ stripSize?: [number, number]
159
+ /** a kept version's own files with the same content, repo relative; set once checked */
160
+ from?: { video?: string; strip?: string }
161
+ }
162
+
163
+ /** a finished render of a cut: its length and rate, its size, the timeline it was rendered from (null: unknown), its
164
+ * files' content */
152
165
  export interface View {
153
166
  mtime: number
154
167
  duration: number
155
168
  fps: number
156
169
  size: [number, number]
157
170
  timeline: Timeline | null
171
+ media?: ViewMedia
158
172
  }
159
173
 
160
- const viewBase = (root: string, id: string, cut: string, mtime: number): string => join(viewDir(root), `${id}--${cut}--${Math.round(mtime)}`)
174
+ export const viewBase = (root: string, id: string, cut: string, mtime: number): string => join(viewDir(root), `${id}--${cut}--${Math.round(mtime)}`)
161
175
  export const viewVideo = (root: string, id: string, cut: string, mtime: number): string => `${viewBase(root, id, cut, mtime)}.mp4`
162
176
  export const viewStrip = (root: string, id: string, cut: string, mtime: number): string => `${viewBase(root, id, cut, mtime)}.strip.png`
163
177
 
@@ -169,10 +183,19 @@ function keepStrip(root: string, dir: string, id: string, c: CutFiles, mtime: nu
169
183
  copyFileSync(sf, kept, constants.COPYFILE_FICLONE)
170
184
  }
171
185
 
172
- /** a kept version by its mtime, null when it was pruned */
186
+ /** a render by its mtime, null when nothing holds its video: neither its clone nor the media store */
173
187
  export function readView(root: string, id: string, cut: string, mtime: number): View | null {
174
188
  const f = `${viewBase(root, id, cut, mtime)}.json`
175
- return existsSync(f) && existsSync(viewVideo(root, id, cut, mtime)) ? (JSON.parse(readFileSync(f, 'utf8')) as View) : null
189
+ if (!existsSync(f)) return null
190
+ const v = JSON.parse(readFileSync(f, 'utf8')) as View
191
+ return v.media?.video || existsSync(viewVideo(root, id, cut, mtime)) ? v : null
192
+ }
193
+
194
+ /** a render's record written whole, through a file beside it renamed */
195
+ export function writeView(root: string, id: string, cut: string, v: View): void {
196
+ const f = `${viewBase(root, id, cut, v.mtime)}.json`
197
+ writeFileSync(`${f}.${process.pid}.tmp`, JSON.stringify(v))
198
+ renameSync(`${f}.${process.pid}.tmp`, f)
176
199
  }
177
200
 
178
201
  function newestView(root: string, id: string, cut: string): View | null {
@@ -230,55 +253,63 @@ export function viewOf(root: string, dir: string, id: string, c: CutFiles, now =
230
253
  timeline = null
231
254
  }
232
255
  const view: View = { mtime, ...p, timeline }
233
- writeFileSync(`${viewBase(root, id, c.cut, mtime)}.json`, JSON.stringify(view))
256
+ writeView(root, id, c.cut, view)
234
257
  keepStrip(root, dir, id, c, mtime)
235
258
  views.set(key, view)
236
- pruneViews(root, id, c.cut)
237
259
  return { view, rendering: false }
238
260
  }
239
261
 
240
- function pruneViews(root: string, id: string, cut: string): void {
241
- const prefix = `${id}--${cut}--`
242
- for (const f of viewsToDrop(root)) if (f.slice(viewDir(root).length + 1).startsWith(prefix)) rmSync(f, { force: true })
243
- }
262
+ export const TRAILER_KIND = 'trailer'
244
263
 
245
- /** the kept renders that go: every one past the newest VIEWS_KEPT of a cut, and every one of a cut its folder no longer
246
- * has (a note keeps its own still) */
247
- export function viewsToDrop(root: string): string[] {
248
- const vd = viewDir(root)
249
- if (!existsSync(vd)) return []
250
- const live = new Set(trailerIds(root).flatMap((id) => cutsOf(join(trailersDir(root), id)).map((c) => `${id}--${c.cut}`)))
251
- const byCut = new Map<string, Set<number>>()
252
- const files = readdirSync(vd)
253
- for (const f of files) {
254
- const m = /^(.+)--(\d+)\./.exec(f)
255
- if (!m) continue
256
- const ms = byCut.get(m[1]!) ?? new Set<number>()
257
- byCut.set(m[1]!, ms.add(Number(m[2])))
264
+ /** where the Space keeps a render's file */
265
+ export const trailerKey = (f: MediaFact, part: 'video' | 'strip'): string => mediaKey(TRAILER_KIND, f, part === 'video' ? 'render.mp4' : 'strip.png')
266
+
267
+ /** the folder of the view clones, relative to the repo: the item of their rows in the media index */
268
+ export const VIEW_ITEM = join(LAYOUT.cache, 'trailer-view')
269
+
270
+ /** a render's video or strip as the page reads it: its clone, else the cut's own file while it is that render (a live
271
+ * cut's out/ file at the same mtime, a version's own file), else a URL the media store signs. `bytes` wants a file:
272
+ * the store's copy is fetched back into the clone's place. null when nothing holds it */
273
+ export async function viewMedia(root: string, id: string, cut: string, mtime: number, part: 'video' | 'strip', o: { bytes?: boolean } = {}): Promise<{ path: string } | { url: string } | null> {
274
+ const v = readView(root, id, cut, mtime)
275
+ if (!v) return null
276
+ const clone = part === 'video' ? viewVideo(root, id, cut, mtime) : viewStrip(root, id, cut, mtime)
277
+ if (existsSync(clone)) return { path: clone }
278
+ const dir = trailerDir(root, id)
279
+ const c = dir ? cutOf(dir, cut) : null
280
+ if (dir && c && part === 'video') {
281
+ const own = videoOf(dir, c)
282
+ if (existsSync(own) && Math.round(statSync(own).mtimeMs) === mtime) return { path: own }
258
283
  }
259
- const kept = new Set(
260
- [...byCut].flatMap(([cut, ms]) =>
261
- live.has(cut)
262
- ? [...ms]
263
- .sort((x, y) => y - x)
264
- .slice(0, VIEWS_KEPT)
265
- .map((m) => `${cut}--${m}`)
266
- : [],
267
- ),
268
- )
269
- return files.filter((f) => !kept.has(/^(.+--\d+)\./.exec(f)?.[1] ?? '')).map((f) => join(vd, f))
284
+ const fact = v.media?.[part]
285
+ const from = v.media?.from?.[part]
286
+ if (from && fact && existsSync(join(root, from)) && statSync(join(root, from)).size === fact.size) return { path: join(root, from) }
287
+ if (!fact) return null
288
+ const key = trailerKey(fact, part)
289
+ if (o.bytes) {
290
+ const back = await fetchBack(clone, key, fact, { store: root, item: VIEW_ITEM, name: clone.slice(viewDir(root).length + 1) })
291
+ return back ? { path: back } : null
292
+ }
293
+ const url = await signedUrl(key, fact.size)
294
+ return url ? { url } : null
270
295
  }
271
296
 
272
297
  /** the contact strip's grid as src/trailer/stitch.ts lays it: rows of six tiles THUMB_W wide, 6 px apart */
273
298
  const STRIP_COLS = 6
274
299
  const STRIP_PAD = 6
275
300
 
276
- /** the strip's grid, when the file's size fits this timeline's shots */
277
- function stripInfo(file: string, tl: Timeline): CutInfo['strip'] {
278
- if (!existsSync(file) || tl.shots.length === 0) return null
301
+ /** a png's width and height, read from its header */
302
+ export function pngSize(file: string): [number, number] {
279
303
  const head = readFileSync(file).subarray(0, 24)
280
- const w = head.readUInt32BE(16)
281
- const h = head.readUInt32BE(20)
304
+ return [head.readUInt32BE(16), head.readUInt32BE(20)]
305
+ }
306
+
307
+ /** the strip's grid, when its size fits this timeline's shots: read from the clone, else from the render's record */
308
+ function stripInfo(file: string, v: View, tl: Timeline): CutInfo['strip'] {
309
+ if (tl.shots.length === 0) return null
310
+ const wh = existsSync(file) ? pngSize(file) : v.media?.strip ? v.media.stripSize : undefined
311
+ if (!wh) return null
312
+ const [w, h] = wh
282
313
  const cols = Math.min(STRIP_COLS, tl.shots.length)
283
314
  const rows = Math.ceil(tl.shots.length / cols)
284
315
  const tileH = Math.round((THUMB_W * tl.size[1]) / tl.size[0] / 2) * 2
@@ -313,7 +344,7 @@ export function cutInfo(root: string, dir: string, id: string, c: CutFiles): Cut
313
344
  video: view ? { mtime: view.mtime, duration: view.duration, fps: view.fps } : null,
314
345
  rendering: !c.version && rendering,
315
346
  edited: !c.version && c.trailer !== null && view !== null && fileMtime > view.mtime,
316
- strip: timeline && view ? stripInfo(viewStrip(root, id, c.cut, view.mtime), timeline) : null,
347
+ strip: timeline && view ? stripInfo(viewStrip(root, id, c.cut, view.mtime), view, timeline) : null,
317
348
  fileMtime,
318
349
  version: c.version === true,
319
350
  }
@@ -362,7 +393,9 @@ export async function frameNote(root: string, trailer: string, input: NewNote, s
362
393
  const f = frameAt(input.time, v.fps, v.duration)
363
394
  const shot = shotAt(tl, f.time)
364
395
  if (!shot) throw new Error(`${input.cut} has no shot`)
365
- await stillAt(viewVideo(root, trailer, input.cut, v.mtime), (f.frame - 0.5) / v.fps, still)
396
+ const video = await viewMedia(root, trailer, input.cut, v.mtime, 'video', { bytes: true })
397
+ if (!video || !('path' in video)) throw new Error(`the render of ${input.cut} on screen is in neither the disk nor the media store`)
398
+ await stillAt(video.path, (f.frame - 0.5) / v.fps, still)
366
399
  return { kind: 'frame', trailer, cut: input.cut, version: String(v.mtime), time: round(f.time), frame: f.frame, shot: shot.name, shotTime: round(f.time - shot.start), section: shot.section }
367
400
  }
368
401
 
@@ -0,0 +1,181 @@
1
+ // the trailer renders as a kind of the media store (wiki build/trailer.md, Renders in the media store): each settled
2
+ // render's clone in the view folder and a kept version's own files, by the facts its view record keeps, and the shots
3
+ // folders (trailer-shots.ts). Kept on the
4
+ // disk: the newest render of each live cut, the render an open frame note was written on, and any render seen in the
5
+ // window. A file goes only when its own bytes hash to the key. The takes and footage cache is never this kind's
6
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { basename, dirname, join, relative } from 'node:path'
8
+ import { factOf, shaOf, shaOfKey } from '../media-store/content.ts'
9
+ import type { MediaFact } from '../media-store/fact.ts'
10
+ import type { MediaKind, MediaRow } from '../media-store/kind.ts'
11
+ import { fetchBack } from '../media-store/remote.ts'
12
+ import { isFrame } from './model.ts'
13
+ import { readAllCached, storeDir } from './store.ts'
14
+ import { cutOf, cutsOf, pngSize, stripOf, TRAILER_KIND, trailerDir, trailerIds, trailerKey, trailerStamp, videoOf, VIEW_ITEM, viewDir, viewOf, writeView, type View } from './trailer-desk.ts'
15
+ import { noteOf } from './trailer-model.ts'
16
+ import { newestShelves, shotFolders, shotRows } from './trailer-shots.ts'
17
+
18
+ /** a view record's name, `<trailer>--<cut>--<mtime>` */
19
+ const BASE_RE = /^(.+?)--(.+)--(\d+)$/
20
+
21
+ interface ViewRecord {
22
+ base: string
23
+ id: string
24
+ cut: string
25
+ v: View
26
+ }
27
+
28
+ function records(root: string): ViewRecord[] {
29
+ const d = viewDir(root)
30
+ if (!existsSync(d)) return []
31
+ return readdirSync(d)
32
+ .filter((f) => f.endsWith('.json'))
33
+ .sort()
34
+ .flatMap((f) => {
35
+ const base = f.slice(0, -'.json'.length)
36
+ const m = BASE_RE.exec(base)
37
+ if (!m) return []
38
+ try {
39
+ return [{ base, id: m[1]!, cut: m[2]!, v: JSON.parse(readFileSync(join(d, f), 'utf8')) as View }]
40
+ } catch {
41
+ return []
42
+ }
43
+ })
44
+ }
45
+
46
+ const sizeOf = (p: string): number | undefined => statSync(p, { throwIfNoEntry: false })?.size
47
+
48
+ /** a version's own file, recorded only when its bytes are the clone's */
49
+ async function sameAs(root: string, file: string, f: MediaFact): Promise<string | undefined> {
50
+ return existsSync(file) && sizeOf(file) === f.size && (await shaOf(file)) === f.sha ? relative(root, file) : undefined
51
+ }
52
+
53
+ export const trailerMedia: MediaKind = {
54
+ kind: TRAILER_KIND,
55
+ storeOf: (root) => (existsSync(join(root, 'trailer')) ? root : null),
56
+ stamp: (root) => `${trailerStamp(root)}#${existsSync(viewDir(root)) ? readdirSync(viewDir(root)).length : 0}#shots:${shotFolders(root).map((f) => `${f.item}@${f.born}`).join(',')}`,
57
+ async scan(root, o) {
58
+ // every settled render gets its record, whether or not the page was opened since
59
+ for (const id of trailerIds(root)) {
60
+ const dir = trailerDir(root, id)
61
+ if (dir) for (const c of cutsOf(dir)) viewOf(root, dir, id, c)
62
+ }
63
+ const rows: MediaRow[] = []
64
+ let budget = o.fill
65
+ let filled = 0
66
+ let left = 0
67
+ const take = (): boolean => {
68
+ if (budget <= 0) {
69
+ left++
70
+ return false
71
+ }
72
+ budget--
73
+ filled++
74
+ return true
75
+ }
76
+ for (const r of records(root)) {
77
+ const media = { ...r.v.media }
78
+ let moved = false
79
+ const video = join(viewDir(root), `${r.base}.mp4`)
80
+ const strip = join(viewDir(root), `${r.base}.strip.png`)
81
+ if (!media.video && existsSync(video) && take()) {
82
+ media.video = await factOf(video)
83
+ moved = true
84
+ }
85
+ if (!media.strip && existsSync(strip) && take()) {
86
+ media.strip = await factOf(strip)
87
+ media.stripSize = pngSize(strip)
88
+ moved = true
89
+ }
90
+ const dir = trailerDir(root, r.id)
91
+ const c = dir ? cutOf(dir, r.cut) : null
92
+ if (!media.from && c?.version && dir && media.video && (media.strip || !existsSync(strip)) && take()) {
93
+ const own = videoOf(dir, c)
94
+ const from = {
95
+ ...(Math.round(statSync(own, { throwIfNoEntry: false })?.mtimeMs ?? -1) === r.v.mtime ? { video: await sameAs(root, own, media.video) } : {}),
96
+ ...(media.strip ? { strip: await sameAs(root, stripOf(dir, c), media.strip) } : {}),
97
+ }
98
+ media.from = Object.fromEntries(Object.entries(from).filter(([, x]) => x !== undefined))
99
+ moved = true
100
+ }
101
+ if (moved) writeView(root, r.id, r.cut, { ...r.v, media })
102
+ const row = (path: string, f: MediaFact | undefined): void => {
103
+ const s = sizeOf(path)
104
+ if (!f) {
105
+ if (s === undefined) rows.push({ item: relative(root, dirname(path)), name: basename(path), fact: null, local: false })
106
+ return
107
+ }
108
+ // a file of another content at that place is never this record's
109
+ if (s !== undefined && s !== f.size) return
110
+ rows.push({ item: relative(root, dirname(path)), name: basename(path), fact: f, local: s === f.size })
111
+ }
112
+ row(video, media.video)
113
+ if (media.strip || existsSync(strip)) row(strip, media.strip)
114
+ if (media.from?.video) row(join(root, media.from.video), media.video)
115
+ if (media.from?.strip) row(join(root, media.from.strip), media.strip)
116
+ }
117
+ for (const f of shotFolders(root)) rows.push(...(await shotRows(root, f, take)))
118
+ return { rows, filled, left }
119
+ },
120
+ async holds(root) {
121
+ const recs = records(root)
122
+ const owner = new Map<string, ViewRecord>()
123
+ for (const r of recs) {
124
+ owner.set(`${VIEW_ITEM}/${r.base}.mp4`, r)
125
+ owner.set(`${VIEW_ITEM}/${r.base}.strip.png`, r)
126
+ for (const p of Object.values(r.v.media?.from ?? {})) if (p) owner.set(`${dirname(p)}/${basename(p)}`, r)
127
+ }
128
+ // the newest render of each live cut: the one the page plays first, and the cut's out/ file is that render
129
+ const newest = new Map<string, number>()
130
+ const live = new Set(trailerIds(root).flatMap((id) => cutsOf(join(root, 'trailer', id)).filter((c) => !c.version).map((c) => `${id}--${c.cut}`)))
131
+ for (const r of recs) if (live.has(`${r.id}--${r.cut}`)) newest.set(`${r.id}--${r.cut}`, Math.max(newest.get(`${r.id}--${r.cut}`) ?? 0, r.v.mtime))
132
+ const open = new Set<string>()
133
+ const used = new Map<string, number>()
134
+ for (const x of readAllCached(storeDir(root)).items) {
135
+ const s = x.item.subject
136
+ if (!isFrame(s)) continue
137
+ const base = `${s.trailer}--${s.cut}--${s.version}`
138
+ if (noteOf(x, 0)?.state === 'open') open.add(base)
139
+ const at = Math.max(Date.parse(x.item.created) || 0, ...x.thread.map((m) => Date.parse(m.at) || 0))
140
+ used.set(base, Math.max(used.get(base) ?? 0, at))
141
+ }
142
+ // a shots folder: the shelf of each trailer's newest build stays, any other goes once quiet, unless a note is open on its cut
143
+ const folders = new Map(shotFolders(root).map((f) => [f.item, f]))
144
+ const shelves = newestShelves([...folders.values()])
145
+ const cutUse = (id: string, cut: string): { open: boolean; at: number } => {
146
+ let at = 0
147
+ let isOpen = false
148
+ for (const [base, t] of used) if (base.startsWith(`${id}--${cut}--`)) at = Math.max(at, t)
149
+ for (const base of open) if (base.startsWith(`${id}--${cut}--`)) isOpen = true
150
+ return { open: isOpen, at }
151
+ }
152
+ return (row) => {
153
+ const f = folders.get(row.item)
154
+ if (f) {
155
+ const u = cutUse(f.trailer, f.cut)
156
+ return { pinned: shelves.has(f.item) || u.open, used: Math.max(f.born, u.at) }
157
+ }
158
+ const r = owner.get(`${row.item}/${row.name}`)
159
+ if (!r) return { pinned: false, used: undefined }
160
+ const pinned = newest.get(`${r.id}--${r.cut}`) === r.v.mtime || open.has(r.base)
161
+ return { pinned, used: Math.max(r.v.mtime, used.get(r.base) ?? 0) }
162
+ }
163
+ },
164
+ async beforePurge(root, _space, r) {
165
+ const want = shaOfKey(r.key)
166
+ const path = join(root, r.item, r.name)
167
+ if (!want || (await shaOf(path)) !== want) throw new Error(`${path} does not hash to its key ${r.key}: kept`)
168
+ },
169
+ }
170
+
171
+ /** a kept version's video on the disk, fetched back from the media store when the disk let it go; null when neither */
172
+ export async function versionVideoBack(root: string, id: string, v: string): Promise<string | null> {
173
+ for (const r of records(root).filter((x) => x.id === id && x.cut === v)) {
174
+ const from = r.v.media?.from?.video
175
+ const f = r.v.media?.video
176
+ if (!from || !f) continue
177
+ const path = join(root, from)
178
+ return fetchBack(path, trailerKey(f, 'video'), f, { store: root, item: dirname(from), name: basename(from) })
179
+ }
180
+ return null
181
+ }
@@ -7,7 +7,7 @@ import { join, relative } from 'node:path'
7
7
  import { bad, NO_STORE, ranged } from './http.ts'
8
8
  import { ID_RE, isFrame } from './model.ts'
9
9
  import { act, appendMessage, deleteRaised, raiseItem, readAllCached, readItem } from './store.ts'
10
- import { cutOf, frameNote, montagePage, trailerDir, trailerIds, trailerInfo, videoOf, viewStrip, viewVideo } from './trailer-desk.ts'
10
+ import { cutOf, frameNote, montagePage, trailerDir, trailerIds, trailerInfo, videoOf, viewMedia } from './trailer-desk.ts'
11
11
  import { CUT_RE, noteOf, TRAILER_ID_RE, type NotePin, type NoteState, type TrailerDesk } from './trailer-model.ts'
12
12
 
13
13
  const clamp = (v: number): number => Number(Math.min(1, Math.max(0, v)).toFixed(4))
@@ -54,7 +54,10 @@ export async function trailerRoutes(req: Request, path: string, root: string, di
54
54
  if (media && req.method === 'GET') {
55
55
  const [, kind, id = '', cut = '', version = ''] = media
56
56
  if (!TRAILER_ID_RE.test(id) || !CUT_RE.test(cut)) return bad(`${path}?`, 404)
57
- return ranged(req, kind === 'video' ? viewVideo(root, id, cut, Number(version)) : viewStrip(root, id, cut, Number(version)))
57
+ const at = await viewMedia(root, id, cut, Number(version), kind === 'video' ? 'video' : 'strip')
58
+ if (!at) return bad(`no render ${id}/${cut} at ${version}: neither the disk nor the media store holds it`, 404)
59
+ // a render the disk let go plays from the Space: the signed URL lives an hour, the browser keeps half of it
60
+ return 'path' in at ? ranged(req, at.path) : new Response(null, { status: 302, headers: { Location: at.url, 'Cache-Control': 'private, max-age=1800' } })
58
61
  }
59
62
  const mont = /^\/api\/trailer\/montage\/([^/]+)\/([^/]+)$/.exec(path)
60
63
  if (mont && req.method === 'GET') {