File size: 8,368 Bytes
6fff8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// 导出面板:画幅 / 分辨率 / 帧率 / 背景音乐
import { useEffect, useRef, useState } from 'react'
import { exportMp4, pickSaveFile, ExportOpts, ExportProgress, RES, Res, Fps, dims, estimateMB, canStreamToDisk, webCodecsOK, fileName } from '../video/export'
import { DURATION } from '../video/timeline'
import { Chip, Switch, cx, fmtTime } from './ui'

export default function ExportPanel({ orient }: { orient: 'l' | 'p' }) {
  const [o, setO] = useState<ExportOpts>({ orient, res: '1080', fps: 30, music: true, toDisk: false })
  const [prog, setProg] = useState<ExportProgress | null>(null)
  const [busy, setBusy] = useState(false)
  const [err, setErr] = useState<string | null>(null)
  const [result, setResult] = useState<{ url: string | null; name: string; size: number; codec: string; disk: boolean } | null>(null)
  const abortRef = useRef<AbortController | null>(null)
  const [supported, setSupported] = useState(true)
  const [disk, setDisk] = useState(false)

  useEffect(() => {
    setSupported(webCodecsOK())
    setDisk(canStreamToDisk())
  }, [])
  useEffect(() => setO((x) => ({ ...x, orient })), [orient])
  const est = estimateMB(o)
  useEffect(() => {
    if (disk) setO((x) => ({ ...x, toDisk: estimateMB(x) > 450 }))
  }, [o.res, o.fps, disk])
  useEffect(() => () => { if (result?.url) URL.revokeObjectURL(result.url) }, [result])

  const start = async () => {
    setErr(null)
    let fw: FileSystemWritableFileStream | undefined
    if (o.toDisk && disk) {
      try {
        fw = await pickSaveFile(o)
      } catch {
        return // 用户取消了保存对话框
      }
    }
    if (result?.url) URL.revokeObjectURL(result.url)
    setResult(null)
    setBusy(true)
    const ac = new AbortController()
    abortRef.current = ac
    try {
      const r = await exportMp4(o, setProg, ac.signal, fw)
      const name = fileName(o)
      if (r.blob) {
        const url = URL.createObjectURL(r.blob)
        setResult({ url, name, size: r.blob.size, codec: r.codec, disk: false })
        const a = document.createElement('a')
        a.href = url
        a.download = name
        document.body.appendChild(a)
        a.click()
        a.remove()
      } else setResult({ url: null, name, size: 0, codec: r.codec, disk: true })
    } catch (e) {
      const m = e instanceof Error ? e.message : String(e)
      if ((e as DOMException)?.name === 'AbortError') setErr('导出已取消')
      else setErr(m)
    } finally {
      setBusy(false)
      abortRef.current = null
    }
  }
  const { W, H } = dims(o)
  const pct = prog ? Math.round(prog.p * 1000) / 10 : 0

  return (
    <div className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr]">
      <div className="rounded-2xl border border-white/10 bg-white/[0.02] p-5 sm:p-6 flex flex-col gap-6">
        <Row label="画幅">
          <Chip active={o.orient === 'l'} onClick={() => setO({ ...o, orient: 'l' })} disabled={busy}>横屏 16:9</Chip>
          <Chip active={o.orient === 'p'} onClick={() => setO({ ...o, orient: 'p' })} disabled={busy}>竖屏 9:16(手机)</Chip>
        </Row>
        <Row label="分辨率">
          {(['1440', '1080', '720'] as Res[]).map((r) => (
            <Chip key={r} active={o.res === r} onClick={() => setO({ ...o, res: r })} disabled={busy}>{RES[r].label}</Chip>
          ))}
        </Row>
        <Row label="帧率">
          {([24, 30, 60] as Fps[]).map((f) => (
            <Chip key={f} active={o.fps === f} onClick={() => setO({ ...o, fps: f })} disabled={busy}>{f} fps</Chip>
          ))}
        </Row>
        <Row label="背景音乐">
          <Switch on={o.music} onChange={(v) => !busy && setO({ ...o, music: v })} label={o.music ? '导出背景音乐' : '不导出背景音乐(保留旁白与音效)'} />
        </Row>
        {disk && (
          <Row label="保存方式">
            <Switch on={o.toDisk} onChange={(v) => !busy && setO({ ...o, toDisk: v })} label={o.toDisk ? '边渲染边写入磁盘(大文件推荐)' : '渲染完成后下载'} />
          </Row>
        )}
        <div className="grid grid-cols-3 gap-3 text-center">
          <Stat k="输出尺寸" v={`${W}×${H}`} />
          <Stat k="时长" v={fmtTime(DURATION)} />
          <Stat k="预计大小" v={`≈${est < 1000 ? Math.round(est) + ' MB' : (est / 1024).toFixed(2) + ' GB'}`} />
        </div>
      </div>

      <div className="rounded-2xl border border-white/10 bg-gradient-to-b from-[#16130e] to-[#0d0d10] p-5 sm:p-6 flex flex-col gap-5">
        <div className="text-[13px] leading-6 text-[#a39d92]">
          视频在你的浏览器里逐帧渲染并编码成 MP4,不上传任何服务器。导出时请保持本页面在前台。2K / 60 帧画面更细腻,但耗时更长、文件更大。
        </div>
        {!supported && <div className="rounded-lg bg-[#b3261e]/15 border border-[#b3261e]/40 p-3 text-[13px] text-[#f2c9b8]">当前浏览器不支持本地视频编码(WebCodecs)。请使用最新版 Chrome 或 Edge 电脑浏览器导出。</div>}
        {busy || prog?.phase === 'done' ? (
          <div className="flex flex-col gap-3">
            <div className="flex items-baseline justify-between">
              <div className="text-[15px] text-[#f3eee4]">{prog?.phase === 'prepare' ? '准备素材与编码器…' : prog?.phase === 'finalize' ? '正在封装 MP4…' : prog?.phase === 'done' ? '导出完成' : '正在渲染'}</div>
              <div className="font-mono text-[22px] text-[#e7cf98] tabular-nums">{pct.toFixed(1)}%</div>
            </div>
            <div className="h-2 rounded-full bg-white/10 overflow-hidden">
              <div className="h-full bg-gradient-to-r from-[#b3261e] via-[#d8763a] to-[#e7cf98] transition-[width]" style={{ width: `${pct}%` }} />
            </div>
            {prog && prog.phase === 'render' && (
              <div className="grid grid-cols-3 gap-2 text-[12px] text-[#a39d92] tabular-nums">
                <div>帧 {prog.frame}/{prog.frames}</div>
                <div className="text-center">速度 {prog.fpsNow.toFixed(1)} 帧/秒</div>
                <div className="text-right">剩余约 {fmtTime(prog.eta)}</div>
              </div>
            )}
            {prog?.codec && <div className="text-[12px] text-[#8f897e]">编码:{prog.codec}</div>}
          </div>
        ) : null}
        {err && <div className="text-[13px] text-[#f2a093]">{err}</div>}
        {result && (
          <div className="rounded-xl border border-[#c9a86a]/40 bg-[#c9a86a]/10 p-4 text-[14px] text-[#f3e6c8] flex flex-col gap-2">
            <div className="font-semibold">{result.disk ? '已保存到你选择的位置' : '已生成,下载已开始'}</div>
            <div className="text-[12px] text-[#cbbf9f] break-all">{result.name}{result.size ? ` · ${(result.size / 1024 / 1024).toFixed(1)} MB` : ''} · {result.codec}</div>
            {result.url && (
              <a href={result.url} download={result.name} className="self-start mt-1 rounded-full bg-[#c9a86a] px-4 py-2 text-[13px] font-semibold text-[#16130e]">再次下载</a>
            )}
          </div>
        )}
        <div className="mt-auto flex gap-3">
          {!busy ? (
            <button onClick={start} disabled={!supported} className={cx('h-12 flex-1 rounded-full text-[15px] font-semibold transition-colors', supported ? 'bg-[#c9a86a] text-[#16130e] hover:bg-[#e7cf98]' : 'bg-white/10 text-white/40')}>
              开始导出 MP4
            </button>
          ) : (
            <button onClick={() => abortRef.current?.abort()} className="h-12 flex-1 rounded-full border border-white/20 text-[15px] text-[#f3eee4] hover:border-[#b3261e]">取消导出</button>
          )}
        </div>
      </div>
    </div>
  )
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-center gap-3">
      <div className="w-20 shrink-0 text-[13px] tracking-widest text-[#8f897e]">{label}</div>
      <div className="flex flex-wrap gap-2">{children}</div>
    </div>
  )
}
function Stat({ k, v }: { k: string; v: string }) {
  return (
    <div className="rounded-xl bg-black/30 px-2 py-3">
      <div className="text-[11px] tracking-widest text-[#8f897e]">{k}</div>
      <div className="mt-1 text-[15px] text-[#f3eee4] tabular-nums">{v}</div>
    </div>
  )
}