Spaces:
Running

Ethscriptions commited on
Commit
4cf4fad
·
verified ·
1 Parent(s): 0a789d0

Step 4-6: 芯片音乐/音效/混音 + 播放器/MP4导出 + 封面文案

Browse files
README.md CHANGED
@@ -113,3 +113,4 @@ earth-online-sun/
113
  - [x] 步骤 1:计划写入 README,推送 HF。
114
  - [x] 步骤 2:TREATMENT.md 文案分镜、48 句旁白稿、edge-tts 配音(共 154.8 秒)、像素字库与世界地图烘焙工具。
115
  - [x] 步骤 3:像素渲染引擎(索引色帧缓冲/调色板时代 LUT/像素字体)+ 12 个场景完成,横竖屏自适应,总长 192.7 秒
 
 
113
  - [x] 步骤 1:计划写入 README,推送 HF。
114
  - [x] 步骤 2:TREATMENT.md 文案分镜、48 句旁白稿、edge-tts 配音(共 154.8 秒)、像素字库与世界地图烘焙工具。
115
  - [x] 步骤 3:像素渲染引擎(索引色帧缓冲/调色板时代 LUT/像素字体)+ 12 个场景完成,横竖屏自适应,总长 192.7 秒
116
+ - [x] 步骤 4-6:纯 JS 采样级芯片音乐与 40 种音效合成(1.7 秒生成整轨)、旁白闪避混音;网页播放器(横/竖屏、章节跳转、全屏);浏览器本地 WebCodecs 导出 MP4(24/30/60 帧,1080p);四平台封面(4:3/3:4/16:9)与可复制标题/描述/话题。
earth-online-sun/web/index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="/favicon.ico" />
7
- <title>App</title>
8
  <script>
9
  document.documentElement.classList.add('dark');
10
  </script>
 
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <link rel="icon" href="/favicon.ico" />
7
+ <title>地球 Online:孙宇晨访谈速通</title>
8
  <script>
9
  document.documentElement.classList.add('dark');
10
  </script>
earth-online-sun/web/package.json CHANGED
@@ -13,16 +13,7 @@
13
  "type-check": "tsc --noEmit --incremental"
14
  },
15
  "dependencies": {
16
- "@surf-ai/theme": "latest",
17
- "react": "19.2.4",
18
- "react-dom": "19.2.4",
19
- "class-variance-authority": "0.7.1",
20
- "clsx": "2.1.1",
21
- "tailwind-merge": "2.6.1",
22
- "lucide-react": "0.454.0",
23
- "next-themes": "0.4.6",
24
- "echarts": "5.6.0",
25
- "echarts-for-react": "3.0.6",
26
  "@radix-ui/react-accordion": "1.2.12",
27
  "@radix-ui/react-aspect-ratio": "1.1.8",
28
  "@radix-ui/react-avatar": "1.1.11",
@@ -49,19 +40,29 @@
49
  "@radix-ui/react-toggle": "1.1.10",
50
  "@radix-ui/react-toggle-group": "1.1.11",
51
  "@radix-ui/react-tooltip": "1.2.8",
52
- "sonner": "1.7.4",
 
 
 
 
53
  "cmdk": "1.1.1",
54
- "vaul": "1.1.2",
 
 
55
  "embla-carousel-react": "8.6.0",
 
 
 
 
56
  "react-day-picker": "9.14.0",
57
- "react-resizable-panels": "4.7.6",
58
  "react-hook-form": "7.72.0",
59
- "@hookform/resolvers": "5.2.2",
60
- "date-fns": "4.1.0",
61
- "zod": "3.25.76",
62
- "@tanstack/react-query": "5.94.5",
63
- "@tanstack/query-core": "5.94.5",
64
- "scheduler": "0.27.0"
65
  },
66
  "devDependencies": {
67
  "@types/react": "19.2.14",
 
13
  "type-check": "tsc --noEmit --incremental"
14
  },
15
  "dependencies": {
16
+ "@hookform/resolvers": "5.2.2",
 
 
 
 
 
 
 
 
 
17
  "@radix-ui/react-accordion": "1.2.12",
18
  "@radix-ui/react-aspect-ratio": "1.1.8",
19
  "@radix-ui/react-avatar": "1.1.11",
 
40
  "@radix-ui/react-toggle": "1.1.10",
41
  "@radix-ui/react-toggle-group": "1.1.11",
42
  "@radix-ui/react-tooltip": "1.2.8",
43
+ "@surf-ai/theme": "latest",
44
+ "@tanstack/query-core": "5.94.5",
45
+ "@tanstack/react-query": "5.94.5",
46
+ "class-variance-authority": "0.7.1",
47
+ "clsx": "2.1.1",
48
  "cmdk": "1.1.1",
49
+ "date-fns": "4.1.0",
50
+ "echarts": "5.6.0",
51
+ "echarts-for-react": "3.0.6",
52
  "embla-carousel-react": "8.6.0",
53
+ "lucide-react": "0.454.0",
54
+ "mp4-muxer": "^5.2.2",
55
+ "next-themes": "0.4.6",
56
+ "react": "19.2.4",
57
  "react-day-picker": "9.14.0",
58
+ "react-dom": "19.2.4",
59
  "react-hook-form": "7.72.0",
60
+ "react-resizable-panels": "4.7.6",
61
+ "scheduler": "0.27.0",
62
+ "sonner": "1.7.4",
63
+ "tailwind-merge": "2.6.1",
64
+ "vaul": "1.1.2",
65
+ "zod": "3.25.76"
66
  },
67
  "devDependencies": {
68
  "@types/react": "19.2.14",
earth-online-sun/web/src/App.tsx CHANGED
@@ -1,24 +1,287 @@
1
- const SURF_LOGO_PATH = "M14.6875 13.333C15.0977 13.333 15.4859 13.5196 15.7422 13.8398L17.8721 16.502C17.9009 16.538 17.9308 16.5721 17.9619 16.6035C18.3091 16.9542 18.7529 17.3405 18.7529 17.834C18.7528 18.3399 18.3428 18.75 17.8369 18.75H17.5713C17.2123 18.75 16.8727 18.5869 16.6484 18.3066L15.4678 16.8311C14.761 15.9479 13.3369 16.4478 13.3369 17.5791V18.6494C13.3369 18.7062 13.2882 18.75 13.2314 18.75H11.3584C10.7127 18.75 10.1016 18.4564 9.69824 17.9521L8.80176 16.8311C8.09497 15.9477 6.66993 16.4478 6.66992 17.5791V18.6494C6.66991 18.7062 6.62124 18.75 6.56445 18.75H4.69141C4.04589 18.75 3.43548 18.4562 3.03223 17.9521L2.13477 16.8311C1.77885 16.3862 1.25293 15.931 1.25293 15.3613V13.4395C1.253 13.3822 1.29729 13.3331 1.35449 13.333C1.7646 13.3332 2.15295 13.5196 2.40918 13.8398L4.53809 16.502C5.24478 17.3853 6.66962 16.886 6.66992 15.7549V14.6836C6.67018 13.9379 7.27483 13.3332 8.02051 13.333C8.43065 13.333 8.81884 13.5197 9.0752 13.8398L11.2051 16.502C11.9097 17.3827 13.3282 16.8887 13.3369 15.7646V14.6836C13.3372 13.9378 13.9417 13.3331 14.6875 13.333ZM14.6875 6.66699C15.0978 6.66702 15.4859 6.85347 15.7422 7.17383L17.8721 9.83594C18.2276 10.2801 18.7526 10.7339 18.7529 11.3027V13.2266C18.7528 13.2833 18.7091 13.333 18.6523 13.333C18.2421 13.3329 17.8539 13.1465 17.5977 12.8262L15.4678 10.1641C14.7609 9.28113 13.3369 9.78089 13.3369 10.9121V11.9824C13.3369 12.7282 12.7321 13.3328 11.9863 13.333C11.5761 13.3329 11.187 13.1465 10.9307 12.8262L8.80176 10.1641C8.09497 9.28072 6.66993 9.78076 6.66992 10.9121V11.9824C6.66992 12.7284 6.06525 13.3329 5.31934 13.333C4.90908 13.3329 4.52094 13.1465 4.26465 12.8262L2.13477 10.1641C1.7788 9.71925 1.25293 9.26403 1.25293 8.69434V6.77344C1.253 6.71621 1.29728 6.6671 1.35449 6.66699C1.76461 6.66714 2.15295 6.85359 2.40918 7.17383L4.53809 9.83594C5.24487 10.7193 6.66989 10.2192 6.66992 9.08789V8.01758C6.66992 7.27168 7.27467 6.66722 8.02051 6.66699C8.43082 6.66699 8.81885 6.85345 9.0752 7.17383L11.2051 9.83594C11.9097 10.7163 13.3279 10.2223 13.3369 9.09863V8.01758C13.3369 7.27161 13.9416 6.6671 14.6875 6.66699ZM2.43555 1.25C2.79488 1.25 3.13499 1.41367 3.35938 1.69434L4.53809 3.16895C5.24485 4.05241 6.66991 3.55228 6.66992 2.4209V1.35059C6.66993 1.29391 6.71874 1.25017 6.77539 1.25H8.64844C9.29394 1.25 9.90438 1.5438 10.3076 2.04785L11.2051 3.16895C11.9097 4.04967 13.3282 3.55564 13.3369 2.43164V1.35059C13.3369 1.29391 13.3857 1.25017 13.4424 1.25H15.3154C15.9609 1.25 16.5714 1.5438 16.9746 2.04785L17.8721 3.16895C18.2275 3.61314 18.7526 4.06689 18.7529 4.63574V6.56055C18.7528 6.61728 18.7091 6.66699 18.6523 6.66699C18.2421 6.66688 17.8539 6.4795 17.5977 6.15918L15.4678 3.49805C14.761 2.61474 13.3371 3.11388 13.3369 4.24512V5.31543C13.3369 6.06126 12.7321 6.66673 11.9863 6.66699C11.5761 6.66693 11.187 6.47955 10.9307 6.15918L8.80176 3.49805C8.095 2.61474 6.67006 3.11388 6.66992 4.24512V5.31543C6.66992 6.06137 6.06525 6.66691 5.31934 6.66699C4.90908 6.66693 4.52094 6.47955 4.26465 6.15918L2.13477 3.49805C2.10558 3.46158 2.07543 3.42725 2.04395 3.39551C1.6966 3.04528 1.25293 2.6583 1.25293 2.16504C1.25317 1.65963 1.66348 1.25 2.16895 1.25H2.43555Z"
 
 
 
 
 
 
2
 
3
- function SurfLogo() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  return (
5
- <svg width="40" height="40" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
6
- <path d={SURF_LOGO_PATH} fill="var(--fg-base, #212121)" />
7
- </svg>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  )
9
  }
10
 
11
- // Frontend API calls should use `src/lib/api.ts`, not absolute `/api/...` URLs.
12
  export default function App() {
 
 
 
13
  return (
14
- <div data-surf-placeholder className="min-h-screen flex flex-col items-center justify-center gap-4 rounded-[14px]" style={{ background: 'var(--bg-chat-nav, #f4f4f4)', border: '1px solid var(--border-strong, rgba(42,42,42,0.08))' }}>
15
- <SurfLogo />
16
- <h1 className="font-black text-[36px] leading-[44px] text-[var(--fg-base,#212121)]">
17
- GM, Builder<span style={{ color: 'var(--brand-100, #ff2882)' }}>.</span>
18
- </h1>
19
- <p className="text-xl leading-7 text-[var(--fg-subtle,#7a7a7a)]">
20
- Start your crypto project here!
21
- </p>
 
 
 
 
 
 
 
 
 
 
 
22
  </div>
23
  )
24
  }
 
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
+ import { Play, Pause, Download, Copy, Check, Maximize, Smartphone, Monitor, Film, Loader2, Archive, X } from 'lucide-react'
3
+ import { renderRGBA, DUR, SCENES } from './film/render'
4
+ import { buildSoundtrack } from './film/audio'
5
+ import { exportMP4, canWebCodecs } from './film/export'
6
+ import { coverCanvas, RATIO_PX, type Ratio } from './film/covers'
7
+ import { PLATFORMS, len, type Platform } from './film/copy'
8
 
9
+ const BASE = import.meta.env.BASE_URL || './'
10
+ const SIZE = { land: [384, 216], port: [216, 384] } as const
11
+ type Orient = keyof typeof SIZE
12
+
13
+ const fmt = (t: number) => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, '0')}`
14
+
15
+ // ---------------- shared soundtrack (built once) ----------------
16
+ let trackPromise: Promise<AudioBuffer> | null = null
17
+ function getTrack(onP: (s: string, p: number) => void) {
18
+ if (!trackPromise) trackPromise = buildSoundtrack(onP).catch(e => { trackPromise = null; throw e })
19
+ return trackPromise
20
+ }
21
+
22
+ // ---------------- player ----------------
23
+ function Player({ orient, setOrient }: { orient: Orient; setOrient: (o: Orient) => void }) {
24
+ const [W, H] = SIZE[orient]
25
+ const canvas = useRef<HTMLCanvasElement>(null)
26
+ const wrap = useRef<HTMLDivElement>(null)
27
+ const [playing, setPlaying] = useState(false)
28
+ const [time, setTime] = useState(0)
29
+ const [loading, setLoading] = useState<string | null>(null)
30
+ const st = useRef({ ctx: null as AudioContext | null, buf: null as AudioBuffer | null, src: null as AudioBufferSourceNode | null, startAt: 0, offset: 0, playing: false })
31
+
32
+ const now = useCallback(() => {
33
+ const s = st.current
34
+ if (s.playing && s.ctx) return Math.min(DUR, s.ctx.currentTime - s.startAt)
35
+ return s.offset
36
+ }, [])
37
+
38
+ // render loop
39
+ useEffect(() => {
40
+ const cv = canvas.current!; cv.width = W; cv.height = H
41
+ const g = cv.getContext('2d')!
42
+ const img = g.createImageData(W, H)
43
+ let raf = 0, last = -1
44
+ const loop = () => {
45
+ const t = now()
46
+ if (st.current.playing && t >= DUR - 0.01) { stopSrc(); st.current.offset = 0; st.current.playing = false; setPlaying(false) }
47
+ if (t !== last) { renderRGBA(t, W, H, img.data); g.putImageData(img, 0, 0); last = t; setTime(t) }
48
+ raf = requestAnimationFrame(loop)
49
+ }
50
+ raf = requestAnimationFrame(loop)
51
+ return () => cancelAnimationFrame(raf)
52
+ // eslint-disable-next-line react-hooks/exhaustive-deps
53
+ }, [W, H])
54
+
55
+ const stopSrc = () => { const s = st.current; if (s.src) { try { s.src.stop() } catch { /* */ } s.src.disconnect(); s.src = null } }
56
+ const startSrc = (offset: number) => {
57
+ const s = st.current
58
+ if (!s.ctx || !s.buf) return
59
+ stopSrc()
60
+ const src = s.ctx.createBufferSource(); src.buffer = s.buf; src.connect(s.ctx.destination)
61
+ src.start(0, offset); s.src = src; s.startAt = s.ctx.currentTime - offset
62
+ }
63
+ const toggle = async () => {
64
+ const s = st.current
65
+ if (s.playing) { s.offset = now(); stopSrc(); s.playing = false; setPlaying(false); return }
66
+ if (!s.ctx) s.ctx = new AudioContext({ sampleRate: 48000 })
67
+ await s.ctx.resume()
68
+ if (!s.buf) {
69
+ setLoading('准备声音 0%')
70
+ try { s.buf = await getTrack((n, p) => setLoading(`准备${n} ${Math.round(p * 100)}%`)) } catch (e) { setLoading(null); alert('声音加载失败:' + (e as Error).message); return }
71
+ setLoading(null)
72
+ }
73
+ if (s.offset >= DUR - 0.05) s.offset = 0
74
+ startSrc(s.offset); s.playing = true; setPlaying(true)
75
+ }
76
+ const seek = (t: number) => {
77
+ const s = st.current
78
+ s.offset = Math.max(0, Math.min(DUR, t))
79
+ if (s.playing) startSrc(s.offset)
80
+ else setTime(s.offset)
81
+ }
82
+ const full = () => { const el = wrap.current; if (!el) return; if (document.fullscreenElement) document.exitFullscreen(); else el.requestFullscreen?.() }
83
+
84
+ const cur = SCENES.findIndex(s => time < s.end)
85
+ return (
86
+ <div className="flex flex-col gap-3">
87
+ <div ref={wrap} className="relative mx-auto w-full bg-black flex items-center justify-center rounded-lg overflow-hidden"
88
+ style={{ maxWidth: orient === 'land' ? 960 : 420 }}>
89
+ <canvas ref={canvas} onClick={toggle} className="w-full h-auto cursor-pointer block" style={{ imageRendering: 'pixelated', aspectRatio: `${W} / ${H}`, maxHeight: '100vh', objectFit: 'contain' }} />
90
+ {!playing && !loading && (
91
+ <button onClick={toggle} aria-label="播放" className="absolute inset-0 m-auto w-16 h-16 rounded-full bg-black/60 border-2 border-yellow-400 flex items-center justify-center hover:scale-105 transition">
92
+ <Play className="w-8 h-8 text-yellow-400 ml-1" />
93
+ </button>
94
+ )}
95
+ {loading && <div className="absolute inset-x-0 bottom-3 mx-auto w-fit px-3 py-1 rounded bg-black/70 text-yellow-300 text-sm flex items-center gap-2"><Loader2 className="w-4 h-4 animate-spin" />{loading}</div>}
96
+ </div>
97
+ <div className="mx-auto w-full flex items-center gap-3" style={{ maxWidth: orient === 'land' ? 960 : 420 }}>
98
+ <button onClick={toggle} className="p-2 rounded bg-yellow-400 text-black" aria-label={playing ? '暂停' : '播放'}>{playing ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}</button>
99
+ <input type="range" min={0} max={DUR} step={0.05} value={time} onChange={e => seek(+e.target.value)} className="flex-1 accent-yellow-400" />
100
+ <span className="text-xs tabular-nums text-neutral-400 w-20 text-right">{fmt(time)} / {fmt(DUR)}</span>
101
+ <button onClick={full} className="p-2 rounded border border-neutral-700" aria-label="全屏"><Maximize className="w-4 h-4" /></button>
102
+ </div>
103
+ <div className="mx-auto w-full flex flex-wrap gap-2 items-center" style={{ maxWidth: orient === 'land' ? 960 : 420 }}>
104
+ <div className="flex rounded overflow-hidden border border-neutral-700 text-sm">
105
+ <button onClick={() => setOrient('land')} className={`px-3 py-1.5 flex items-center gap-1 ${orient === 'land' ? 'bg-yellow-400 text-black' : ''}`}><Monitor className="w-4 h-4" />横屏 16:9</button>
106
+ <button onClick={() => setOrient('port')} className={`px-3 py-1.5 flex items-center gap-1 ${orient === 'port' ? 'bg-yellow-400 text-black' : ''}`}><Smartphone className="w-4 h-4" />竖屏 9:16</button>
107
+ </div>
108
+ <div className="flex gap-1 overflow-x-auto text-xs py-1">
109
+ {SCENES.map((s, i) => (
110
+ <button key={s.id} onClick={() => seek(s.start + 0.01)} className={`shrink-0 px-2 py-1 rounded border ${i === cur ? 'border-yellow-400 text-yellow-300' : 'border-neutral-800 text-neutral-400'}`}>{s.title}</button>
111
+ ))}
112
+ </div>
113
+ </div>
114
+ </div>
115
+ )
116
+ }
117
+
118
+ // ---------------- export ----------------
119
+ function Exporter({ orient }: { orient: Orient }) {
120
+ const [fps, setFps] = useState<24 | 30 | 60>(30)
121
+ const [o, setO] = useState<Orient>(orient)
122
+ const [busy, setBusy] = useState(false)
123
+ const [msg, setMsg] = useState('')
124
+ const [p, setP] = useState(0)
125
+ const [out, setOut] = useState<{ url: string; name: string; size: number } | null>(null)
126
+ const sig = useRef({ aborted: false })
127
+ useEffect(() => setO(orient), [orient])
128
+ const go = async () => {
129
+ setBusy(true); setOut(null); setP(0); sig.current = { aborted: false }
130
+ try {
131
+ setMsg('准备声音…')
132
+ const audio = await getTrack((n, q) => setMsg(`准备${n} ${Math.round(q * 100)}%`))
133
+ const [W, H] = SIZE[o]
134
+ const { blob, ext } = await exportMP4({ W, H, scale: 5, fps, audio, signal: sig.current, onProgress: (q, m) => { setP(q); setMsg(m) } })
135
+ const name = `地球Online_孙宇晨访谈_${o === 'land' ? '横屏1920x1080' : '竖屏1080x1920'}_${fps}fps.${ext}`
136
+ const url = URL.createObjectURL(blob)
137
+ setOut({ url, name, size: blob.size })
138
+ const a = document.createElement('a'); a.href = url; a.download = name; a.click()
139
+ setMsg('完成')
140
+ } catch (e) { setMsg('导出中断:' + (e as Error).message) }
141
+ setBusy(false)
142
+ }
143
+ return (
144
+ <section className="rounded-xl border border-neutral-800 p-4 flex flex-col gap-3">
145
+ <h2 className="text-lg font-bold flex items-center gap-2"><Film className="w-5 h-5 text-yellow-400" />导出 MP4(在你的浏览器本地渲染)</h2>
146
+ <div className="flex flex-wrap gap-3 items-center text-sm">
147
+ <span className="text-neutral-400">画幅</span>
148
+ {(['land', 'port'] as Orient[]).map(k => (
149
+ <button key={k} disabled={busy} onClick={() => setO(k)} className={`px-3 py-1.5 rounded border ${o === k ? 'border-yellow-400 bg-yellow-400 text-black' : 'border-neutral-700'}`}>{k === 'land' ? '横屏 1920×1080' : '竖屏 1080×1920'}</button>
150
+ ))}
151
+ <span className="text-neutral-400 ml-2">帧率</span>
152
+ {([24, 30, 60] as const).map(f => (
153
+ <button key={f} disabled={busy} onClick={() => setFps(f)} className={`px-3 py-1.5 rounded border ${fps === f ? 'border-yellow-400 bg-yellow-400 text-black' : 'border-neutral-700'}`}>{f} fps</button>
154
+ ))}
155
+ </div>
156
+ <div className="flex gap-2 items-center">
157
+ {!busy ? (
158
+ <button onClick={go} className="px-4 py-2 rounded bg-yellow-400 text-black font-bold flex items-center gap-2"><Download className="w-4 h-4" />开始导出</button>
159
+ ) : (
160
+ <button onClick={() => { sig.current.aborted = true }} className="px-4 py-2 rounded border border-red-500 text-red-400 flex items-center gap-2"><X className="w-4 h-4" />取消</button>
161
+ )}
162
+ {out && <a href={out.url} download={out.name} className="text-sm underline text-yellow-300">再次下载({(out.size / 1048576).toFixed(1)} MB)</a>}
163
+ </div>
164
+ {(busy || msg) && (
165
+ <div className="flex flex-col gap-1">
166
+ <div className="h-2 rounded bg-neutral-800 overflow-hidden"><div className="h-full bg-yellow-400 transition-all" style={{ width: `${p * 100}%` }} /></div>
167
+ <div className="text-xs text-neutral-400">{msg}</div>
168
+ </div>
169
+ )}
170
+ <p className="text-xs text-neutral-500">{canWebCodecs() ? '使用硬件编码快速导出,通常比实时播放快。导出期间请保持本页在前台。' : '当前浏览器不支持快速导出,将以实时录制方式导出(约 3 分钟)。推荐使用最新版 Chrome / Edge / Safari。'}</p>
171
+ </section>
172
+ )
173
+ }
174
+
175
+ // ---------------- covers + copy ----------------
176
+ function useCopy() {
177
+ const [k, setK] = useState('')
178
+ const copy = async (key: string, s: string) => {
179
+ try { await navigator.clipboard.writeText(s) } catch {
180
+ const ta = document.createElement('textarea'); ta.value = s; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove()
181
+ }
182
+ setK(key); setTimeout(() => setK(''), 1200)
183
+ }
184
+ return { k, copy }
185
+ }
186
+ function CopyBtn({ id, text, c }: { id: string; text: string; c: ReturnType<typeof useCopy> }) {
187
+ return <button onClick={() => c.copy(id, text)} className="shrink-0 px-2 py-1 rounded border border-neutral-700 text-xs flex items-center gap-1 hover:border-yellow-400">{c.k === id ? <Check className="w-3 h-3 text-green-400" /> : <Copy className="w-3 h-3" />}{c.k === id ? '已复制' : '复制'}</button>
188
+ }
189
+ function Cover({ p, ratio, label }: { p: Platform; ratio: Ratio; label: string }) {
190
+ const [url, setUrl] = useState('')
191
+ useEffect(() => { setUrl(coverCanvas(ratio, p.cover).toDataURL('image/jpeg', 0.95)) }, [p, ratio])
192
+ const [w, h] = RATIO_PX[ratio]
193
+ return (
194
+ <figure className="flex flex-col gap-1">
195
+ {url ? <img src={url} alt={`${p.name} ${label}`} className="w-full rounded border border-neutral-800" style={{ imageRendering: 'pixelated', aspectRatio: `${w}/${h}` }} /> : <div style={{ aspectRatio: `${w}/${h}` }} className="bg-neutral-900 rounded" />}
196
+ <figcaption className="flex items-center justify-between text-xs text-neutral-400">
197
+ <span>{label} · {w * 5}×{h * 5}</span>
198
+ {url && <a href={url} download={`${p.name}_封面_${ratio.replace(':', 'x')}.jpg`} className="flex items-center gap-1 text-yellow-300"><Download className="w-3 h-3" />下载</a>}
199
+ </figcaption>
200
+ </figure>
201
+ )
202
+ }
203
+ function PlatformCard({ p }: { p: Platform }) {
204
+ const c = useCopy()
205
+ const topics = p.topics.map(t => `#${t}`).join(' ')
206
+ const tl = len(p.title)
207
+ const all = `${p.title}\n\n${p.desc}\n\n${topics}`
208
+ return (
209
+ <div className="rounded-xl border border-neutral-800 p-4 flex flex-col gap-3">
210
+ <div className="flex items-center justify-between">
211
+ <h3 className="font-bold text-base">{p.name}</h3>
212
+ <CopyBtn id="all" text={all} c={c} />
213
+ </div>
214
+ <div className={`grid gap-2 ${p.covers.some(x => x.ratio === '3:4') ? 'grid-cols-[3fr_4fr]' : 'grid-cols-[4fr_5.33fr]'} items-start`}>
215
+ {p.covers.map(x => <Cover key={x.ratio} p={p} ratio={x.ratio} label={x.label} />)}
216
+ </div>
217
+ <div className="flex flex-col gap-1">
218
+ <div className="flex items-center justify-between text-xs text-neutral-400"><span>标题</span><span className={tl > p.titleMax ? 'text-red-400' : 'text-green-400'}>{tl}/{p.titleMax} 字</span></div>
219
+ <div className="flex gap-2 items-start"><p className="flex-1 text-sm bg-neutral-900 rounded p-2">{p.title}</p><CopyBtn id="t" text={p.title} c={c} /></div>
220
+ </div>
221
+ <div className="flex flex-col gap-1">
222
+ <div className="text-xs text-neutral-400">描述</div>
223
+ <div className="flex gap-2 items-start"><p className="flex-1 text-sm bg-neutral-900 rounded p-2 whitespace-pre-line max-h-40 overflow-auto">{p.desc}</p><CopyBtn id="d" text={p.desc} c={c} /></div>
224
+ </div>
225
+ <div className="flex flex-col gap-1">
226
+ <div className="flex items-center justify-between text-xs text-neutral-400"><span>话题</span><span className="text-green-400">{p.topics.length}{p.topicMax ? `/${p.topicMax}` : ' 个(不限)'}</span></div>
227
+ <div className="flex gap-2 items-start"><p className="flex-1 text-sm bg-neutral-900 rounded p-2 text-sky-300">{topics}</p><CopyBtn id="g" text={topics} c={c} /></div>
228
+ </div>
229
+ </div>
230
+ )
231
+ }
232
+
233
+ // ---------------- live photos ----------------
234
+ interface LiveItem { name: string; title: string; jpg: string; mp4?: string }
235
+ function LivePhotos() {
236
+ const [items, setItems] = useState<LiveItem[] | null>(null)
237
+ useEffect(() => { fetch(`${BASE}film/live/manifest.json`).then(r => r.ok ? r.json() : []).then(setItems).catch(() => setItems([])) }, [])
238
  return (
239
+ <section className="rounded-xl border border-neutral-800 p-4 flex flex-col gap-3">
240
+ <div className="flex flex-wrap items-center justify-between gap-2">
241
+ <h2 className="text-lg font-bold flex items-center gap-2"><Archive className="w-5 h-5 text-yellow-400" />实况图(Live Photo:jpg + mov)</h2>
242
+ <a href={`${BASE}film/livephotos.zip`} download className="px-4 py-2 rounded bg-yellow-400 text-black font-bold text-sm flex items-center gap-2"><Download className="w-4 h-4" />下载全部(zip)</a>
243
+ </div>
244
+ <p className="text-xs text-neutral-500">每组为同名 .jpg + .mov(3:4,1080×1440,3 秒)。用 iPhone 隔空投送或导入相册后即为实况照片,可直接发小红书 / 抖音图文。</p>
245
+ {items === null ? <div className="text-sm text-neutral-400">加载中…</div> : (
246
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
247
+ {items.map(it => (
248
+ <figure key={it.name} className="flex flex-col gap-1">
249
+ {it.mp4
250
+ ? <video src={`${BASE}film/live/${it.mp4}`} poster={`${BASE}film/live/${it.jpg}`} muted loop playsInline autoPlay className="w-full rounded border border-neutral-800" style={{ aspectRatio: '3/4', imageRendering: 'pixelated' }} />
251
+ : <img src={`${BASE}film/live/${it.jpg}`} alt={it.title} className="w-full rounded border border-neutral-800" style={{ aspectRatio: '3/4' }} />}
252
+ <figcaption className="text-xs text-neutral-400">{it.title}</figcaption>
253
+ </figure>
254
+ ))}
255
+ </div>
256
+ )}
257
+ </section>
258
  )
259
  }
260
 
 
261
  export default function App() {
262
+ const [orient, setOrient] = useState<Orient>('land')
263
+ useEffect(() => { if (window.innerHeight > window.innerWidth) setOrient('port') }, [])
264
+ const total = useMemo(() => fmt(DUR), [])
265
  return (
266
+ <div className="min-h-screen bg-[#0b0d1a] text-neutral-100">
267
+ <main className="mx-auto max-w-6xl px-3 sm:px-6 py-4 sm:py-8 flex flex-col gap-6">
268
+ <header className="flex flex-col gap-1">
269
+ <div className="text-xs tracking-widest text-yellow-400">EARTH ONLINE · v2026.10</div>
270
+ <h1 className="text-2xl sm:text-3xl font-black">地球 Online:孙宇晨访谈速通</h1>
271
+ <p className="text-sm text-neutral-400">像素 RPG 风格解说 · 旁白 + 原创芯片音乐 + 音效 · 全长 {total}</p>
272
+ </header>
273
+ <Player orient={orient} setOrient={setOrient} />
274
+ <Exporter orient={orient} />
275
+ <section className="flex flex-col gap-3">
276
+ <h2 className="text-lg font-bold">发布文案与封面</h2>
277
+ <div className="grid md:grid-cols-2 gap-4">{PLATFORMS.map(p => <PlatformCard key={p.id} p={p} />)}</div>
278
+ </section>
279
+ <LivePhotos />
280
+ <footer className="text-xs text-neutral-500 pb-16 flex flex-col gap-1">
281
+ <p>本片为访谈观点整理与解读,不构成任何投资建议。访谈:孙宇晨 × 邵艾伦(文字整理:律动BlockBeats)。</p>
282
+ <p>画面、音乐、音效由程序实时生成;旁白为 AI 合成;像素字体 Fusion Pixel(SIL OFL 1.1);地图数据 Natural Earth(公有领域)。</p>
283
+ </footer>
284
+ </main>
285
  </div>
286
  )
287
  }
earth-online-sun/web/src/film/audio.ts ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Original chiptune score + synthesized SFX + narration, mixed offline into one AudioBuffer.
2
+ // Same buffer drives live playback and MP4 export, so what you hear is what you export.
3
+ import { SCENES, LINES, DUR } from './timeline'
4
+ import { allCues } from './render'
5
+
6
+ export const SR = 48000
7
+
8
+ // ---------- music theory ----------
9
+ const NOTE: Record<string, number> = { C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11 }
10
+ const midi = (n: string, oct: number) => 12 * (oct + 1) + NOTE[n]
11
+ const hz = (m: number) => 440 * Math.pow(2, (m - 69) / 12)
12
+ type Chord = { root: string; q: 'M' | 'm' | 'd' | 's' }
13
+ const ch = (s: string): Chord => {
14
+ const m = s.match(/^([A-G][#b]?)(m|dim|sus)?$/)!
15
+ return { root: m[1], q: m[2] === 'm' ? 'm' : m[2] === 'dim' ? 'd' : m[2] === 'sus' ? 's' : 'M' }
16
+ }
17
+ const tones = (c: Chord) => {
18
+ const r = NOTE[c.root]
19
+ const iv = c.q === 'M' ? [0, 4, 7] : c.q === 'm' ? [0, 3, 7] : c.q === 'd' ? [0, 3, 6] : [0, 5, 7]
20
+ return iv.map(i => r + i)
21
+ }
22
+
23
+ interface Section { bpm: number; prog: string[]; drums: 0 | 1 | 2; lead: number; arp: number; bass: number; seed: number; from?: number; to?: number }
24
+ // per scene score (times are local to the scene; from/to clip the music)
25
+ const SCORE: Record<string, Section[]> = {
26
+ boot: [{ bpm: 100, prog: ['Am', 'F', 'C', 'G'], drums: 0, lead: 0, arp: 0.6, bass: 0.5, seed: 1, from: 3.0, to: 9.6 }, { bpm: 112, prog: ['F', 'G', 'Am', 'C'], drums: 2, lead: 1, arp: 0.7, bass: 1, seed: 2, from: 9.6 }],
27
+ save: [{ bpm: 112, prog: ['C', 'G', 'Am', 'F'], drums: 1, lead: 0.8, arp: 0.7, bass: 1, seed: 3 }],
28
+ kit: [{ bpm: 112, prog: ['F', 'G', 'Em', 'Am'], drums: 1, lead: 1, arp: 0.6, bass: 1, seed: 4 }],
29
+ auto: [{ bpm: 120, prog: ['Am', 'Em', 'F', 'G'], drums: 2, lead: 0.6, arp: 1, bass: 1, seed: 5 }],
30
+ stats: [{ bpm: 108, prog: ['Dm', 'G', 'C', 'Am'], drums: 1, lead: 0.8, arp: 0.6, bass: 1, seed: 6 }],
31
+ fog: [{ bpm: 90, prog: ['Am', 'Bb', 'Am', 'E'], drums: 0, lead: 0.4, arp: 0.5, bass: 0.7, seed: 7, from: 1.6 }],
32
+ world: [{ bpm: 116, prog: ['F', 'C', 'G', 'Am'], drums: 2, lead: 1, arp: 0.7, bass: 1, seed: 8 }],
33
+ translate: [{ bpm: 104, prog: ['C', 'G', 'Am', 'Em'], drums: 1, lead: 0.7, arp: 0.7, bass: 1, seed: 9 }],
34
+ patch: [{ bpm: 124, prog: ['Em', 'C', 'G', 'D'], drums: 2, lead: 0.8, arp: 0.8, bass: 1, seed: 10 }],
35
+ iq: [{ bpm: 108, prog: ['Am', 'F', 'Dm', 'E'], drums: 1, lead: 0.6, arp: 0.7, bass: 0.8, seed: 11 }],
36
+ flywheel: [{ bpm: 116, prog: ['C', 'Am', 'F', 'G'], drums: 2, lead: 1, arp: 0.8, bass: 1, seed: 12 }],
37
+ cont: [{ bpm: 92, prog: ['F', 'G', 'Em', 'Am', 'F', 'G', 'C', 'C'], drums: 1, lead: 1, arp: 0.6, bass: 0.9, seed: 13 }],
38
+ }
39
+
40
+ function rng(a: number) { return () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296 } }
41
+
42
+ // ---------- synth primitives (direct sample synthesis into Float32Arrays) ----------
43
+ type Bus = Float32Array
44
+ type Wave = 'p12' | 'p25' | 'p50' | 'tri' | 'saw' | 'sine'
45
+ class Synth {
46
+ noise: Float32Array
47
+ noiseShort: Float32Array
48
+ constructor() {
49
+ // NES-style LFSR noise (long and short mode), 1 s each
50
+ const mk = (short: boolean) => {
51
+ const d = new Float32Array(SR)
52
+ let reg = 1, v = 0
53
+ for (let i = 0; i < d.length; i++) {
54
+ if (i % 3 === 0) { const bit = (reg ^ (reg >> (short ? 6 : 1))) & 1; reg = (reg >> 1) | (bit << 14); v = reg & 1 ? 1 : -1 }
55
+ d[i] = v * 0.8
56
+ }
57
+ return d
58
+ }
59
+ this.noise = mk(false); this.noiseShort = mk(true)
60
+ }
61
+ tone(dest: Bus, type: Wave, f: number, t: number, dur: number, vol: number, o: { a?: number; r?: number; slide?: number; vib?: number } = {}) {
62
+ if (t < 0 || dur <= 0 || vol <= 0) return
63
+ const i0 = Math.round(t * SR), n = Math.round(dur * SR)
64
+ const a = Math.max(1, Math.round((o.a ?? 0.005) * SR)), r = Math.max(1, Math.round(Math.min(o.r ?? 0.05, dur) * SR))
65
+ const duty = type === 'p12' ? 0.125 : type === 'p25' ? 0.25 : 0.5
66
+ const amp = type === 'p12' ? 1.6 : type === 'p25' ? 1.1 : 0.8
67
+ let ph = 0
68
+ const lnS = o.slide ? Math.log(o.slide) / n : 0
69
+ const vibS = Math.round(0.12 * SR)
70
+ for (let k = 0; k < n; k++) {
71
+ const j = i0 + k; if (j >= dest.length) break
72
+ let fr = f
73
+ if (lnS) fr = f * Math.exp(lnS * k)
74
+ if (o.vib && k > vibS) fr *= 1 + o.vib * Math.sin(2 * Math.PI * 5.5 * (k / SR))
75
+ ph += fr / SR; ph -= Math.floor(ph)
76
+ let v: number
77
+ if (type === 'tri') v = 4 * Math.abs(ph - 0.5) - 1
78
+ else if (type === 'saw') v = (2 * ph - 1) * 0.6
79
+ else if (type === 'sine') v = Math.sin(2 * Math.PI * ph)
80
+ else v = ((ph < duty ? 1 : 0) - duty) * amp
81
+ const env = k < a ? k / a : k > n - r ? (n - k) / r : 1
82
+ dest[j] += v * env * vol
83
+ }
84
+ }
85
+ hit(dest: Bus, t: number, dur: number, vol: number, rate = 1, short = false, o: { hp?: number; lp?: number; rateEnd?: number } = {}) {
86
+ if (t < 0 || vol <= 0) return
87
+ const src = short ? this.noiseShort : this.noise
88
+ const i0 = Math.round(t * SR), n = Math.round(dur * SR)
89
+ const kd = Math.log(0.001) / n
90
+ const lnR = o.rateEnd ? Math.log(o.rateEnd / rate) / n : 0
91
+ const aL = o.lp ? 1 - Math.exp(-2 * Math.PI * o.lp / SR) : 1
92
+ const aH = o.hp ? 1 - Math.exp(-2 * Math.PI * o.hp / SR) : 0
93
+ let pos = (t * 7919) % src.length, lpS = 0, hpS = 0
94
+ for (let k = 0; k < n; k++) {
95
+ const j = i0 + k; if (j >= dest.length) break
96
+ const rr = lnR ? rate * Math.exp(lnR * k) : rate
97
+ pos += rr; if (pos >= src.length) pos -= src.length
98
+ let v = src[pos | 0]
99
+ lpS += aL * (v - lpS); v = lpS
100
+ if (aH) { hpS += aH * (v - hpS); v = v - hpS }
101
+ dest[j] += v * vol * Math.exp(kd * k)
102
+ }
103
+ }
104
+ }
105
+
106
+ // ---------- music ----------
107
+ function writeMusic(sy: Synth, bus: Bus, leadBus: Bus) {
108
+ for (const sc of SCENES) {
109
+ const secs = SCORE[sc.id]
110
+ const sceneLen = sc.end - sc.start
111
+ for (const s of secs) {
112
+ const beat = 60 / s.bpm, six = beat / 4
113
+ const r = rng(s.seed * 977)
114
+ const from = s.from ?? 0, to = Math.min(s.to ?? sceneLen, sceneLen)
115
+ // translate: music stops when the world collapses
116
+ const stopAt = sc.id === 'translate' ? (sc.lines[2].start - sc.start) + (sc.lines[2].end - sc.lines[2].start) * 0.75 : to
117
+ const end = Math.min(to, stopAt)
118
+ // pre-generate a 2-bar motif (scale degrees over chord tones) and reuse with variation
119
+ const motif: (number | null)[] = []
120
+ for (let i = 0; i < 16; i++) motif.push(r() < 0.28 ? null : Math.floor(r() * 5))
121
+ let step = 0
122
+ for (let lt = from; lt < end - 0.01; lt += six, step++) {
123
+ const T = sc.start + lt
124
+ const bar = Math.floor(step / 16), inBar = step % 16
125
+ const chord = ch(s.prog[bar % s.prog.length])
126
+ const tn = tones(chord)
127
+ const rootM = midi(chord.root, 2)
128
+ // fade-out near scene end
129
+ const fade = Math.min(1, (sceneLen - lt) / 0.6, (lt - from) / 0.3 + 0.2)
130
+ // bass (triangle) 8ths with octave bounce
131
+ if (s.bass > 0 && inBar % 2 === 0) {
132
+ const m = rootM + (inBar % 8 === 4 ? 12 : 0) + (inBar === 14 ? 7 : 0)
133
+ sy.tone(bus, 'tri', hz(m), T, six * 1.8, 0.32 * s.bass * fade, { r: 0.03 })
134
+ }
135
+ // arpeggio (12.5% pulse) 16ths
136
+ if (s.arp > 0) {
137
+ const k = [0, 1, 2, 1][inBar % 4] + (inBar >= 8 ? 1 : 0)
138
+ const m = 12 * 5 + tn[k % 3] + (k >= 3 ? 12 : 0)
139
+ sy.tone(bus, 'p12', hz(m), T, six * 0.9, 0.045 * s.arp * fade, { r: 0.02 })
140
+ }
141
+ // lead (25% pulse), 8th grid, motif from chord tones + passing tones
142
+ if (s.lead > 0 && inBar % 2 === 0 && bar % 4 !== 3) {
143
+ const d = motif[(inBar + (bar % 2) * 8) % 16]
144
+ if (d !== null) {
145
+ const scale = [0, 2, 4, 7, 9]
146
+ const base = 12 * 5 + NOTE[chord.root]
147
+ const m = d < 3 ? base + (tones(chord)[d] - NOTE[chord.root] + 12) % 12 : base + scale[d]
148
+ const len = r() < 0.3 ? six * 4 : six * 2
149
+ sy.tone(leadBus, 'p25', hz(m + 12), T, len * 0.95, 0.07 * s.lead * fade, { vib: 0.006, r: 0.04 })
150
+ }
151
+ }
152
+ // turnaround fill on the 4th bar of each phrase
153
+ if (s.lead > 0 && bar % 4 === 3 && inBar % 2 === 0) {
154
+ const m = 12 * 6 + tn[(inBar / 2) % 3] + (inBar >= 8 ? 12 : 0)
155
+ sy.tone(leadBus, 'p50', hz(m), T, six * 1.6, 0.04 * s.lead * fade)
156
+ }
157
+ // drums
158
+ if (s.drums > 0) {
159
+ const kick = inBar === 0 || inBar === 8 || (s.drums === 2 && (inBar === 6 || inBar === 10))
160
+ const snare = inBar === 4 || inBar === 12
161
+ if (kick) sy.tone(bus, 'tri', 160, T, 0.12, 0.5 * fade, { slide: 0.25, r: 0.04 })
162
+ if (snare) sy.hit(bus, T, 0.14, 0.22 * fade, 1, false, { hp: 900 })
163
+ if (inBar % 2 === 0 || s.drums === 2) sy.hit(bus, T, 0.035, (inBar % 4 === 2 ? 0.08 : 0.05) * fade, 1, true, { hp: 6000 })
164
+ if (bar % 8 === 7 && inBar >= 12) sy.hit(bus, T, 0.08, 0.15 * fade, 0.7, false, { hp: 500 })
165
+ }
166
+ }
167
+ // long pad drones for the quiet sections
168
+ if (s.drums === 0) {
169
+ for (let lt = from, b = 0; lt < end - 0.05; lt += beat * 4, b++) {
170
+ const chord = ch(s.prog[b % s.prog.length])
171
+ for (const n of tones(chord)) sy.tone(bus, 'p50', hz(12 * 4 + n), sc.start + lt, Math.min(beat * 4, end - lt), 0.025, { a: 0.4, r: 0.6 })
172
+ }
173
+ }
174
+ }
175
+ }
176
+ // final cadence chord under the end card
177
+ const last = SCENES[SCENES.length - 1]
178
+ const tEnd = last.lines[last.lines.length - 1].end + 1.0
179
+ for (const n of [0, 4, 7, 12, 16]) sy.tone(bus, n > 7 ? 'p25' : 'p50', hz(60 + n), tEnd, DUR - tEnd - 0.2, 0.045, { a: 0.05, r: 2.5, vib: 0.004 })
180
+ sy.tone(bus, 'tri', hz(36), tEnd, DUR - tEnd - 0.2, 0.35, { r: 2.5 })
181
+ }
182
+
183
+ // ---------- SFX ----------
184
+ function sfx(sy: Synth, d: Bus, id: string, t: number, g: number) {
185
+ const T = (f: number, at: number, dur: number, v: number, type: Parameters<Synth['tone']>[1] = 'p25', o: Parameters<Synth["tone"]>[6] = {}) => sy.tone(d, type, f, t + at, dur, v * g, o)
186
+ const N = (at: number, dur: number, v: number, rate = 1, short = false, o: Parameters<Synth['hit']>[6] = {}) => sy.hit(d, t + at, dur, v * g, rate, short, o)
187
+ const arp = (ms: number[], step: number, v: number, type: Parameters<Synth['tone']>[1] = 'p25', len = step) => ms.forEach((m, i) => T(hz(m), i * step, len, v, type))
188
+ switch (id) {
189
+ case 'boot': arp([48, 55, 60, 64, 67, 72], 0.07, 0.12, 'p50', 0.2); T(hz(36), 0, 1.6, 0.25, 'tri', { r: 1 }); break
190
+ case 'blip': T(hz(84), 0, 0.05, 0.12, 'p50'); break
191
+ case 'tick': T(hz(96), 0, 0.03, 0.08, 'p12'); break
192
+ case 'select': arp([79, 84], 0.05, 0.13, 'p50'); break
193
+ case 'confirm': arp([72, 76, 79, 84], 0.045, 0.13, 'p25'); break
194
+ case 'pop': T(600, 0, 0.08, 0.16, 'p50', { slide: 2.2 }); break
195
+ case 'coin': T(hz(83), 0, 0.07, 0.14, 'p50'); T(hz(88), 0.07, 0.3, 0.14, 'p50', { r: 0.25 }); break
196
+ case 'whoosh': case 'trans': N(0, 0.32, 0.16, 0.4, false, { lp: 3000, rateEnd: 2.2 }); break
197
+ case 'title': arp([60, 64, 67, 72, 76, 79, 84], 0.06, 0.12, 'p25', 0.3); N(0, 0.6, 0.12, 0.5, false, { lp: 1800 }); T(hz(36), 0, 1.2, 0.35, 'tri', { r: 0.8 }); break
198
+ case 'stamp': T(140, 0, 0.18, 0.55, 'tri', { slide: 0.3 }); N(0, 0.18, 0.3, 0.8, false, { lp: 1500 }); break
199
+ case 'thud': T(110, 0, 0.25, 0.5, 'tri', { slide: 0.4 }); N(0, 0.2, 0.18, 0.5, false, { lp: 800 }); break
200
+ case 'chime': arp([88, 91, 96], 0.09, 0.07, 'p12', 0.6); break
201
+ case 'levelup': arp([67, 72, 76, 79, 84, 88, 91], 0.055, 0.12, 'p25', 0.12); T(hz(96), 0.4, 0.5, 0.1, 'p50', { r: 0.4, vib: 0.01 }); break
202
+ case 'equip': T(hz(72), 0, 0.06, 0.14, 'p50'); T(hz(79), 0.06, 0.06, 0.14, 'p50'); N(0, 0.25, 0.08, 2, true, { hp: 4000 }); T(hz(91), 0.12, 0.25, 0.1, 'p12', { r: 0.2 }); break
203
+ case 'switch': T(hz(60), 0, 0.05, 0.2, 'p50'); T(hz(72), 0.05, 0.12, 0.2, 'p50'); break
204
+ case 'data': for (let i = 0; i < 8; i++) T(hz(84 + ((i * 7) % 12)), i * 0.035, 0.03, 0.06, 'p12'); break
205
+ case 'print': T(hz(77), 0, 0.04, 0.08, 'p12'); N(0, 0.06, 0.06, 3, true, { hp: 3000 }); break
206
+ case 'alarm': T(880, 0, 0.12, 0.12, 'p50'); T(660, 0.12, 0.12, 0.12, 'p50'); break
207
+ case 'fall': T(1200, 0, 0.8, 0.12, 'p25', { slide: 0.2 }); break
208
+ case 'rise': T(200, 0, 1.0, 0.1, 'p25', { slide: 4 }); break
209
+ case 'wind': N(0, 2.2, 0.08, 0.15, false, { lp: 700 }); break
210
+ case 'march': for (let i = 0; i < 6; i++) N(i * 0.22, 0.05, 0.12, 0.6, true, { lp: 1200 }); break
211
+ case 'reveal': arp([60, 67, 72, 76, 79, 84, 88], 0.09, 0.09, 'p50', 0.5); N(0, 1.2, 0.08, 0.3, false, { hp: 2000, rateEnd: 1.5 }); break
212
+ case 'radar': T(hz(81), 0, 0.5, 0.08, 'sine', { r: 0.45 }); T(hz(81), 0.6, 0.5, 0.05, 'sine', { r: 0.45 }); break
213
+ case 'cross': N(0, 0.12, 0.25, 1.5, false, { hp: 1000 }); T(220, 0, 0.15, 0.2, 'saw', { slide: 0.5 }); break
214
+ case 'zap': T(1600, 0, 0.18, 0.08, 'p12', { slide: 0.15 }); break
215
+ case 'count': for (let i = 0; i < 10; i++) T(hz(72 + i), i * 0.06, 0.04, 0.07, 'p12'); break
216
+ case 'question': T(hz(72), 0, 0.12, 0.13, 'p50'); T(hz(79), 0.14, 0.25, 0.13, 'p50', { slide: 1.06 }); break
217
+ case 'gear': for (let i = 0; i < 6; i++) N(i * 0.09, 0.04, 0.1, 1.2, true, { hp: 1500 }); break
218
+ case 'glitch': for (let i = 0; i < 6; i++) T(100 + ((i * 397) % 1500), i * 0.04, 0.04, 0.1, 'p12'); N(0, 0.25, 0.15, 3, true); break
219
+ case 'powerdown': T(900, 0, 1.4, 0.18, 'p25', { slide: 0.04 }); T(450, 0, 1.4, 0.12, 'tri', { slide: 0.05 }); N(0.2, 1.0, 0.08, 1, false, { rateEnd: 0.05, lp: 2000 }); break
220
+ case 'download': for (let i = 0; i < 12; i++) T(hz(76 + (i % 4) * 2), i * 0.09, 0.05, 0.05, 'p12'); break
221
+ case 'nerf': T(hz(64), 0, 0.12, 0.15, 'p50'); T(hz(58), 0.12, 0.3, 0.15, 'p50', { slide: 0.8 }); break
222
+ case 'buff': arp([72, 79, 84], 0.06, 0.13, 'p25'); break
223
+ case 'error': T(150, 0, 0.35, 0.35, 'saw'); T(158, 0, 0.35, 0.25, 'p50'); N(0, 0.4, 0.2, 0.6); T(150, 0.45, 0.35, 0.3, 'saw'); break
224
+ case 'shrink': T(1000, 0, 1.0, 0.1, 'p12', { slide: 0.3 }); break
225
+ case 'curse': [52, 55, 58, 61].forEach((m, i) => T(hz(m), i * 0.12, 1.2, 0.08, 'saw', { vib: 0.02, r: 0.8 })); T(hz(28), 0, 1.6, 0.35, 'tri', { r: 1 }); break
226
+ case 'save': arp([72, 76, 79, 84, 79, 84, 88], 0.08, 0.1, 'p50', 0.15); break
227
+ case 'end': arp([60, 64, 67, 72], 0.15, 0.08, 'p12', 1.4); break
228
+ }
229
+ }
230
+
231
+ // ---------- VO ----------
232
+ const base = () => (import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? './'
233
+ export async function loadVO(onProgress?: (p: number) => void) {
234
+ let done = 0
235
+ const ctx = new OfflineAudioContext(1, 1, SR)
236
+ return Promise.all(LINES.map(async l => {
237
+ const url = `${base()}film/vo/${String(l.i).padStart(2, '0')}.mp3`
238
+ const ab = await (await fetch(url)).arrayBuffer()
239
+ const buf = await ctx.decodeAudioData(ab)
240
+ onProgress?.(++done / LINES.length)
241
+ return buf.getChannelData(0)
242
+ }))
243
+ }
244
+
245
+ const tick = () => new Promise(r => setTimeout(r, 0))
246
+
247
+ /** render the full soundtrack (stereo, 48 kHz) */
248
+ export async function buildSoundtrack(onProgress?: (stage: string, p: number) => void): Promise<AudioBuffer> {
249
+ const len = Math.ceil(DUR * SR)
250
+ onProgress?.('旁白', 0)
251
+ const vo = await loadVO(p => onProgress?.('旁白', p))
252
+ onProgress?.('音乐', 0.2); await tick()
253
+ const sy = new Synth()
254
+ const music = new Float32Array(len), lead = new Float32Array(len), sfxB = new Float32Array(len), voB = new Float32Array(len)
255
+ writeMusic(sy, music, lead)
256
+ onProgress?.('音效', 0.5); await tick()
257
+ for (const c of allCues()) sfx(sy, sfxB, c.id, c.t, c.g)
258
+ LINES.forEach((l, i) => { const d = vo[i], o = Math.round(l.start * SR); for (let k = 0; k < d.length && o + k < len; k++) voB[o + k] += d[k] })
259
+ onProgress?.('混音', 0.8); await tick()
260
+
261
+ // lead echo: two slightly different delay lines for stereo width
262
+ const echo = (D: number) => {
263
+ const e = new Float32Array(len), n = Math.round(D * SR), aL = 1 - Math.exp(-2 * Math.PI * 2400 / SR)
264
+ let lp = 0
265
+ for (let i = n; i < len; i++) { lp += aL * (lead[i - n] + 0.32 * e[i - n] - lp); e[i] = lp }
266
+ return e
267
+ }
268
+ const eL = echo(0.27), eR = echo(0.30)
269
+ // ducking envelope on music
270
+ const duck = new Float32Array(len).fill(1)
271
+ const BASE = 0.55, DUCK = 0.22
272
+ for (const l of LINES) {
273
+ const a = Math.round((l.start - 0.15) * SR), b = Math.round(l.start * SR), c = Math.round(l.end * SR), d = Math.round((l.end + 0.35) * SR)
274
+ for (let i = Math.max(0, a); i < Math.min(len, d); i++) {
275
+ const g = i < b ? 1 - (1 - DUCK / BASE) * (i - a) / (b - a) : i < c ? DUCK / BASE : DUCK / BASE + (1 - DUCK / BASE) * (i - c) / (d - c)
276
+ if (g < duck[i]) duck[i] = g
277
+ }
278
+ }
279
+ const L = new Float32Array(len), R = new Float32Array(len)
280
+ let hp = 0
281
+ const aH = 1 - Math.exp(-2 * Math.PI * 90 / SR)
282
+ for (let i = 0; i < len; i++) {
283
+ const m = BASE * duck[i]
284
+ hp += aH * (voB[i] - hp)
285
+ const v = voB[i] - hp
286
+ L[i] = (music[i] + lead[i] + eL[i] * 0.35) * m + sfxB[i] * 0.85 + v
287
+ R[i] = (music[i] + lead[i] + eR[i] * 0.35) * m + sfxB[i] * 0.85 + v
288
+ }
289
+ // peak limiter (instant attack, 80 ms release) at -1 dBFS
290
+ const TH = 0.89, rel = Math.exp(-1 / (0.08 * SR))
291
+ let env = 0
292
+ for (let i = 0; i < len; i++) {
293
+ const pk = Math.max(Math.abs(L[i]), Math.abs(R[i]))
294
+ env = pk > env ? pk : env * rel + pk * (1 - rel)
295
+ const g = env > TH ? TH / env : 1
296
+ L[i] *= g; R[i] *= g
297
+ }
298
+ const buf = new AudioBuffer({ length: len, numberOfChannels: 2, sampleRate: SR })
299
+ buf.copyToChannel(L, 0); buf.copyToChannel(R, 1)
300
+ onProgress?.('完成', 1)
301
+ return buf
302
+ }
earth-online-sun/web/src/film/copy.ts ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copy-ready titles / descriptions / topics per platform, with each platform's limits.
2
+ import type { Ratio, CoverText } from './covers'
3
+
4
+ export interface Platform {
5
+ id: string; name: string
6
+ titleMax: number; topicMax: number | null
7
+ covers: { ratio: Ratio; label: string }[]
8
+ title: string; desc: string; topics: string[]
9
+ cover: CoverText
10
+ }
11
+
12
+ const BASE_DESC = `孙宇晨在最新访谈里,把人生讲成了一款「地球Online」。
13
+ 这期用像素RPG的方式,三分钟速通:
14
+ ▸ 读档:2016年《财富自由之路》里的腾讯、比特币、特斯拉、英伟达
15
+ ▸ 新手装备:孙学、薄肌、黄毛
16
+ ▸ 自动驾驶:九成交给AI,一成自己微调;拿不准就问三个大模型取中策
17
+ ▸ 角色状态:物质上是富人,身体上是穷人;肌肉是身体的银行账户
18
+ ▸ 战争迷雾:先派斥候探图,看100套房再买,开图就是开挂
19
+ ▸ 世界地图:商机要全球性发现
20
+ ▸ 翻译器:crypto 把货币翻译成机器听得懂的语言
21
+ ▸ 版本补丁:房地产削弱、AI加强,版本不能回滚
22
+ ▸ 飞轮:先自由,后财富;中彩票是诅咒
23
+ ▸ 体验大于意义,先上路
24
+
25
+ 访谈:孙宇晨 × 邵艾伦(文字整理:律动BlockBeats)
26
+ 本片为访谈观点整理与解读,不构成任何投资建议。`
27
+
28
+ export const PLATFORMS: Platform[] = [
29
+ {
30
+ id: 'xhs', name: '小红书', titleMax: 20, topicMax: 10,
31
+ covers: [{ ratio: '3:4', label: '竖版 3:4' }, { ratio: '4:3', label: '横版 4:3' }],
32
+ title: '孙宇晨最新访谈:人生就是开图游戏',
33
+ desc: `把孙宇晨最新访谈做成了一款像素RPG🎮
34
+ 开图就是开挂|身体是最后的底牌|体验大于意义
35
+
36
+ ${BASE_DESC}`,
37
+ topics: ['孙宇晨', '财富自由', '认知升级', 'AI', '个人成长', '像素风', '访谈解读', '加密货币', '人生游戏', '自律'],
38
+ cover: { l1: '孙宇晨', l2: '人生开图攻略', chips: ['开图 = 开挂', '身体是穷人', '版本不能回滚'] },
39
+ },
40
+ {
41
+ id: 'douyin', name: '抖音', titleMax: 30, topicMax: 5,
42
+ covers: [{ ratio: '3:4', label: '竖版 3:4' }, { ratio: '4:3', label: '横版 4:3' }],
43
+ title: '速通孙宇晨最新访谈:开图就是开挂,体验大于意义',
44
+ desc: `孙宇晨说:地球Online也会更新版本,而且不能回滚。三分钟像素RPG速通他的最新访谈。
45
+ 本片为访谈观点整理与解读,不构成任何投资建议。`,
46
+ topics: ['孙宇晨', '财富自由', '认知', 'AI', '像素游戏'],
47
+ cover: { l1: '孙宇晨', l2: '最新访谈速通', chips: ['开图 = 开挂', 'AI托管人生', '先自由后财富'] },
48
+ },
49
+ {
50
+ id: 'bili', name: 'B站', titleMax: 80, topicMax: 10,
51
+ covers: [{ ratio: '4:3', label: '视频封面 4:3' }, { ratio: '16:9', label: '个人空间 16:9' }],
52
+ title: '【像素RPG】三分钟速通孙宇晨最新访谈:AI托管人生、开图即开挂、版本不能回滚|地球Online 2026版本更新公告',
53
+ desc: `${BASE_DESC}
54
+
55
+ 画面、音乐、音效均为程序原创生成;旁白为AI合成。像素字体:Fusion Pixel(OFL)。`,
56
+ topics: ['孙宇晨', '访谈', '财富自由', '人工智能', '认知', '像素', '8bit', '知识分享', '加密货币', '人生'],
57
+ cover: { l1: '孙宇晨', l2: '版本更新公告', chips: ['AI托管人生', '开图 = 开挂', '版本不能回滚'] },
58
+ },
59
+ {
60
+ id: 'wx', name: '视频号', titleMax: 16, topicMax: null,
61
+ covers: [{ ratio: '3:4', label: '个人主页卡片 3:4' }, { ratio: '4:3', label: '分享卡片 4:3' }],
62
+ title: '孙宇晨:开图就是开挂',
63
+ desc: `孙宇晨最新访谈像素速通:认知是一切,身体是底牌,先自由后财富,体验大于意义。
64
+ 本片为访谈观点整理与解读,不构成任何投资建议。`,
65
+ topics: ['孙宇晨', '财富自由', '认知升级', 'AI', '访谈', '个人成长', '像素风', '人生感悟'],
66
+ cover: { l1: '孙宇晨', l2: '开图就是开挂', chips: ['认知 = 一切', '体验 > 意义'] },
67
+ },
68
+ ]
69
+
70
+ export const len = (s: string) => [...s].length
earth-online-sun/web/src/film/covers.ts ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Platform covers: drawn with the same pixel engine as the film.
2
+ import { FB, C, LUT_ID, present, hash2 } from './px'
3
+ import { text, textC, measure } from './font'
4
+ import { stars, earth, hero, coin } from './art'
5
+ import { tag, sparkle, win } from './ui'
6
+
7
+ export type Ratio = '4:3' | '3:4' | '16:9'
8
+ export const RATIO_PX: Record<Ratio, [number, number]> = { '4:3': [288, 216], '3:4': [216, 288], '16:9': [384, 216] }
9
+ export const COVER_SCALE = 5
10
+
11
+ export interface CoverText { l1: string; l2: string; chips: string[] }
12
+
13
+ export function drawCover(r: Ratio, v: CoverText, t = 2.2): FB {
14
+ const [W, H] = RATIO_PX[r]
15
+ const fb = new FB(W, H)
16
+ const por = H > W
17
+ fb.vgrad(0, 0, W, H, [C.abyss, C.night, C.deep, C.navy])
18
+ stars(fb, t, 0.02, 3)
19
+ // earth
20
+ const er = Math.round(Math.min(W, H) * (por ? 0.34 : 0.4))
21
+ const ex = por ? W / 2 : W - er * 0.6, ey = por ? H - 24 + er * 0 : H * 0.7
22
+ earth(fb, ex, ey, er, 210, t)
23
+ // orbiting coins + sparkles
24
+ coin(fb, ex - er - 6, ey - er * 0.5, 0.05, 'B', C.PGOLD, 9)
25
+ for (let i = 0; i < 9; i++) sparkle(fb, (hash2(i, 7) * W) | 0, (hash2(i, 3) * H * 0.6) | 0, 0.4 + hash2(i, 9) * 0.6, i % 3 ? C.white : C.PGOLD)
26
+ // hero standing on the planet
27
+ hero(fb, ex - 16, ey - er - 46, 0, 'cheer', false, C.lgold, 2)
28
+ // top badge
29
+ const badge = 'EARTH ONLINE v2026.10'
30
+ tag(fb, badge, por ? (W - measure(badge, 8) - 6) / 2 : 8, 7, C.PRED)
31
+ // titles
32
+ const s1 = por ? 4 : 4, s2 = 2
33
+ const tx = por ? W / 2 : 10
34
+ const y1 = por ? 20 : 26
35
+ const draw = (s: string, y: number, sc: number, grad: number[]) => por
36
+ ? textC(fb, s, tx, y, grad[0], { scale: sc, outline: C.ink, grad })
37
+ : text(fb, s, tx, y, grad[0], { scale: sc, outline: C.ink, grad })
38
+ draw(v.l1, y1, s1, [C.white, C.lgold, C.PGOLD, C.orange])
39
+ draw(v.l2, y1 + 14 * s1 + 4, s2, [C.white, C.cyan, C.sky])
40
+ // chips
41
+ let cy = y1 + 14 * s1 + 14 * s2 + 12
42
+ if (por) {
43
+ let x = 8, row: string[] = [], rows: string[][] = []
44
+ for (const c of v.chips) { const w = measure(c, 8) + 10; if (x + w > W - 8 && row.length) { rows.push(row); row = []; x = 8 } row.push(c); x += w }
45
+ if (row.length) rows.push(row)
46
+ for (const rw of rows) {
47
+ const tw = rw.reduce((a, c) => a + measure(c, 8) + 10, -4)
48
+ let xx = (W - tw) / 2
49
+ for (const c of rw) { xx += tag(fb, c, xx, cy, C.PGOLD, C.ink) + 4 }
50
+ cy += 15
51
+ }
52
+ } else {
53
+ for (const c of v.chips) { tag(fb, c, 10, cy, C.PGOLD, C.ink); cy += 15 }
54
+ }
55
+ // dialog-like strap at the bottom (landscape) / above planet (portrait)
56
+ const strap = '孙宇晨 × 邵艾伦 访谈速通'
57
+ const sw = measure(strap, 8) + 16
58
+ const sx = por ? (W - sw) / 2 : 8, sy = H - 22
59
+ win(fb, sx, sy, sw, 16, 'blue')
60
+ text(fb, strap, sx + 8, sy + 3, C.white, { size: 8 })
61
+ return fb
62
+ }
63
+
64
+ /** render cover to a full-size canvas */
65
+ export function coverCanvas(r: Ratio, v: CoverText): HTMLCanvasElement {
66
+ const fb = drawCover(r, v)
67
+ const [W, H] = RATIO_PX[r]
68
+ const small = document.createElement('canvas'); small.width = W; small.height = H
69
+ const sctx = small.getContext('2d')!
70
+ const img = sctx.createImageData(W, H); present(fb, LUT_ID, img.data); sctx.putImageData(img, 0, 0)
71
+ const big = document.createElement('canvas'); big.width = W * COVER_SCALE; big.height = H * COVER_SCALE
72
+ const b = big.getContext('2d')!; b.imageSmoothingEnabled = false; b.drawImage(small, 0, 0, big.width, big.height)
73
+ return big
74
+ }
earth-online-sun/web/src/film/export.ts ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Local, in-browser MP4 export: WebCodecs (H.264 + AAC/Opus) → mp4-muxer.
2
+ // Fallback: real-time MediaRecorder capture when WebCodecs is missing (older Safari / Firefox).
3
+ import { Muxer, ArrayBufferTarget } from 'mp4-muxer'
4
+ import { renderRGBA, DUR } from './render'
5
+
6
+ export interface ExportOpts {
7
+ W: number; H: number // native pixel size
8
+ scale: number // integer upscale
9
+ fps: 24 | 30 | 60
10
+ audio: AudioBuffer
11
+ onProgress: (p: number, msg: string) => void
12
+ signal: { aborted: boolean }
13
+ limit?: number // optional: only export the first N seconds (preview/testing)
14
+ }
15
+
16
+ export const canWebCodecs = () => typeof window !== 'undefined' && 'VideoEncoder' in window && 'VideoFrame' in window
17
+
18
+ async function pickVideo(w: number, h: number, fps: number) {
19
+ const bitrate = Math.round(w * h * fps * 0.16)
20
+ for (const codec of ['avc1.640033', 'avc1.64002a', 'avc1.640028', 'avc1.4d0033', 'avc1.42e033', 'avc1.42002a']) {
21
+ const cfg: VideoEncoderConfig = { codec, width: w, height: h, bitrate, framerate: fps, avc: { format: 'avc' }, latencyMode: 'quality' }
22
+ try { const r = await VideoEncoder.isConfigSupported(cfg); if (r.supported) return cfg } catch { /* try next */ }
23
+ try { const c2 = { ...cfg, hardwareAcceleration: 'prefer-software' as const }; const r = await VideoEncoder.isConfigSupported(c2); if (r.supported) return c2 } catch { /* next */ }
24
+ }
25
+ return null
26
+ }
27
+ async function pickAudio() {
28
+ if (!('AudioEncoder' in window)) return null
29
+ for (const [codec, kind] of [['mp4a.40.2', 'aac'], ['opus', 'opus']] as const) {
30
+ const cfg: AudioEncoderConfig = { codec, sampleRate: 48000, numberOfChannels: 2, bitrate: 192000 }
31
+ try { const r = await AudioEncoder.isConfigSupported(cfg); if (r.supported) return { cfg, kind } } catch { /* next */ }
32
+ }
33
+ return null
34
+ }
35
+
36
+ export async function exportMP4(o: ExportOpts): Promise<{ blob: Blob; ext: string }> {
37
+ const { W, H, scale, fps, audio, onProgress, signal } = o
38
+ const LEN = Math.min(DUR, o.limit ?? DUR)
39
+ const ow = W * scale, oh = H * scale
40
+ const vcfg = await pickVideo(ow, oh, fps)
41
+ const acfg = await pickAudio()
42
+ if (!vcfg || !acfg) return recordRealtime(o)
43
+
44
+ const target = new ArrayBufferTarget()
45
+ const muxer = new Muxer({
46
+ target, fastStart: 'in-memory', firstTimestampBehavior: 'offset',
47
+ video: { codec: 'avc', width: ow, height: oh, frameRate: fps },
48
+ audio: { codec: acfg.kind, numberOfChannels: 2, sampleRate: 48000 },
49
+ })
50
+ let err: unknown = null
51
+ const venc = new VideoEncoder({ output: (c, m) => muxer.addVideoChunk(c, m), error: e => { err = e } })
52
+ venc.configure(vcfg)
53
+ const aenc = new AudioEncoder({ output: (c, m) => muxer.addAudioChunk(c, m), error: e => { err = e } })
54
+ aenc.configure(acfg.cfg)
55
+
56
+ // audio first (fast)
57
+ onProgress(0, '编码音频')
58
+ const SR = 48000, total = Math.min(audio.length, Math.ceil(LEN * SR)), CH = 4800
59
+ const L = audio.getChannelData(0), R = audio.numberOfChannels > 1 ? audio.getChannelData(1) : L
60
+ for (let i = 0; i < total; i += CH) {
61
+ const n = Math.min(CH, total - i), data = new Float32Array(n * 2)
62
+ data.set(L.subarray(i, i + n), 0); data.set(R.subarray(i, i + n), n)
63
+ const ad = new AudioData({ format: 'f32-planar', sampleRate: SR, numberOfFrames: n, numberOfChannels: 2, timestamp: Math.round((i / SR) * 1e6), data })
64
+ aenc.encode(ad); ad.close()
65
+ }
66
+ await aenc.flush()
67
+
68
+ // video
69
+ const small = makeCanvas(W, H), big = makeCanvas(ow, oh)
70
+ const sctx = small.getContext('2d') as CanvasRenderingContext2D
71
+ const bctx = big.getContext('2d') as CanvasRenderingContext2D
72
+ bctx.imageSmoothingEnabled = false
73
+ const img = sctx.createImageData(W, H)
74
+ const N = Math.round(LEN * fps), dur = Math.round(1e6 / fps)
75
+ const t0 = performance.now()
76
+ for (let i = 0; i < N; i++) {
77
+ if (signal.aborted) { try { venc.close(); aenc.close() } catch { /* */ } throw new Error('已取消') }
78
+ if (err) throw err
79
+ renderRGBA(i / fps, W, H, img.data)
80
+ sctx.putImageData(img, 0, 0)
81
+ bctx.drawImage(small as CanvasImageSource, 0, 0, ow, oh)
82
+ const vf = new VideoFrame(big as CanvasImageSource, { timestamp: Math.round((i * 1e6) / fps), duration: dur })
83
+ venc.encode(vf, { keyFrame: i % (fps * 2) === 0 }); vf.close()
84
+ while (venc.encodeQueueSize > 6) await new Promise(r => setTimeout(r, 1))
85
+ if (i % 10 === 0) {
86
+ const el = (performance.now() - t0) / 1000, eta = (el / (i + 1)) * (N - i - 1)
87
+ onProgress((i + 1) / N, `渲染画面 ${i + 1}/${N} 帧 · 剩余约 ${Math.ceil(eta)} 秒`)
88
+ await new Promise(r => setTimeout(r, 0))
89
+ }
90
+ }
91
+ onProgress(1, '封装 MP4')
92
+ await venc.flush()
93
+ if (err) throw err
94
+ muxer.finalize()
95
+ return { blob: new Blob([target.buffer], { type: 'video/mp4' }), ext: 'mp4' }
96
+ }
97
+
98
+ // canvas helper that works with or without OffscreenCanvas
99
+ function makeCanvas(w: number, h: number): OffscreenCanvas | HTMLCanvasElement {
100
+ if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(w, h)
101
+ const c = document.createElement('canvas'); c.width = w; c.height = h; return c
102
+ }
103
+
104
+ /** real-time fallback: canvas.captureStream + MediaRecorder (mp4 where supported, else webm) */
105
+ async function recordRealtime(o: ExportOpts): Promise<{ blob: Blob; ext: string }> {
106
+ const { W, H, scale, fps, audio, onProgress, signal } = o
107
+ if (typeof MediaRecorder === 'undefined') throw new Error('此浏览器不支持本地导出,请使用最新版 Chrome / Edge / Safari')
108
+ const ow = W * scale, oh = H * scale
109
+ const big = document.createElement('canvas'); big.width = ow; big.height = oh
110
+ const bctx = big.getContext('2d')!; bctx.imageSmoothingEnabled = false
111
+ const small = document.createElement('canvas'); small.width = W; small.height = H
112
+ const sctx = small.getContext('2d')!; const img = sctx.createImageData(W, H)
113
+ const ac = new AudioContext({ sampleRate: 48000 })
114
+ const dst = ac.createMediaStreamDestination()
115
+ const src = ac.createBufferSource(); src.buffer = audio; src.connect(dst)
116
+ const stream = new MediaStream([...big.captureStream(fps).getVideoTracks(), ...dst.stream.getAudioTracks()])
117
+ const types = ['video/mp4;codecs=avc1.640028,mp4a.40.2', 'video/mp4', 'video/webm;codecs=vp9,opus', 'video/webm']
118
+ const mime = types.find(t => MediaRecorder.isTypeSupported(t)) || ''
119
+ const rec = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 12_000_000 })
120
+ const chunks: Blob[] = []
121
+ rec.ondataavailable = e => e.data.size && chunks.push(e.data)
122
+ const done = new Promise<void>(r => (rec.onstop = () => r()))
123
+ rec.start(1000)
124
+ const start = ac.currentTime + 0.1
125
+ src.start(start)
126
+ await new Promise<void>(resolve => {
127
+ const tick = () => {
128
+ if (signal.aborted) { rec.stop(); resolve(); return }
129
+ const t = ac.currentTime - start
130
+ if (t >= DUR) { resolve(); return }
131
+ renderRGBA(Math.max(0, t), W, H, img.data); sctx.putImageData(img, 0, 0); bctx.drawImage(small, 0, 0, ow, oh)
132
+ onProgress(Math.max(0, t) / DUR, `实时录制中(此浏览器不支持快速导出)${Math.floor(Math.max(0, t))}/${Math.floor(DUR)} 秒`)
133
+ requestAnimationFrame(tick)
134
+ }
135
+ tick()
136
+ })
137
+ if (rec.state !== 'inactive') rec.stop()
138
+ await done; src.stop(); ac.close()
139
+ if (signal.aborted) throw new Error('已取消')
140
+ const isMp4 = mime.startsWith('video/mp4')
141
+ return { blob: new Blob(chunks, { type: isMp4 ? 'video/mp4' : 'video/webm' }), ext: isMp4 ? 'mp4' : 'webm' }
142
+ }
earth-online-sun/web/src/film/glyphs.json CHANGED
The diff for this file is too large to render. See raw diff
 
earth-online-sun/web/src/film/ui.ts CHANGED
@@ -50,7 +50,7 @@ export function arrowDown(fb: FB, x: number, y: number, t: number) {
50
  }
51
 
52
  /** horizontal bar with segment marks */
53
- export function bar(fb: FB, x: number, y: number, w: number, h: number, v: number, col: number, back = C.ink, hi = C.white) {
54
  fb.rect(x - 1, y - 1, w + 2, h + 2, C.ink)
55
  fb.rect(x, y, w, h, back)
56
  const fw = Math.round(w * clamp(v))
@@ -59,7 +59,7 @@ export function bar(fb: FB, x: number, y: number, w: number, h: number, v: numbe
59
  }
60
 
61
  /** pixel chip label */
62
- export function tag(fb: FB, s: string, x: number, y: number, bg: number, fg = C.white, size: FontSize = 8) {
63
  const w = measure(s, size) + 6, h = lineH(size) + 2
64
  fb.rect(x + 1, y, w - 2, h, bg); fb.rect(x, y + 1, w, h - 2, bg)
65
  text(fb, s, x + 3, y + 1, fg, { size })
 
50
  }
51
 
52
  /** horizontal bar with segment marks */
53
+ export function bar(fb: FB, x: number, y: number, w: number, h: number, v: number, col: number, back: number = C.ink, hi: number = C.white) {
54
  fb.rect(x - 1, y - 1, w + 2, h + 2, C.ink)
55
  fb.rect(x, y, w, h, back)
56
  const fw = Math.round(w * clamp(v))
 
59
  }
60
 
61
  /** pixel chip label */
62
+ export function tag(fb: FB, s: string, x: number, y: number, bg: number, fg: number = C.white, size: FontSize = 8) {
63
  const w = measure(s, size) + 6, h = lineH(size) + 2
64
  fb.rect(x + 1, y, w - 2, h, bg); fb.rect(x, y + 1, w, h - 2, bg)
65
  text(fb, s, x + 3, y + 1, fg, { size })