Compare commits
2
Commits
6ed3e169e4
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60fbbced7d | ||
|
|
82b1fa0d47 |
No files matched your search
@@ -1,3 +1,7 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
# 运行时数据(预设 / 设置 / LRC),由服务器自动创建,不提交到仓库
|
||||||
|
data/
|
||||||
|
data-test/
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
# OBS Lower Third · LRC 字幕
|
||||||
|
|
||||||
|
OBS 浏览器源用的「下三分之一条 + LRC 字幕」管理系统。
|
||||||
|
|
||||||
|
- **外观预设**:自定义 HTML/CSS 模板,用 `{{字段名}}` 占位。
|
||||||
|
- **内容预设**:把具体文字填入外观预设,激活后显示在 OBS 中。
|
||||||
|
- **LRC 字幕(新增)**:导入 LRC、过滤版权/制作信息、自由选择起止句,打点后第一句立即出现,后续严格按 LRC 时间轴显示。
|
||||||
|
- **持久化**:所有预设、LRC、设置保存在 `data/` 下的 JSON 文件里,不再写死在源代码中。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
默认端口 `30001`:
|
||||||
|
|
||||||
|
| 页面 | 地址 | 用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 管理面板 | <http://localhost:30001/manage.html> | 外观 / 内容 / LRC 预设,打点控制 |
|
||||||
|
| OBS 浏览器源 | <http://localhost:30001/widget.html> | 添加到 OBS Browser Source |
|
||||||
|
| 旧版管理页 | <http://localhost:30001/admin.html> | 兼容保留,仅管理外观预设 |
|
||||||
|
|
||||||
|
OBS 中添加 **浏览器源(Browser Source)**,URL 填 `http://127.0.0.1:30001/widget.html`,建议分辨率与画布一致,勾选「关闭源时关闭页面」可选。页面背景透明,字幕和下三分之一条会直接叠加到画面上。
|
||||||
|
|
||||||
|
环境变量:
|
||||||
|
|
||||||
|
| 变量 | 默认值 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `PORT` | `30001` | HTTP / WebSocket 端口 |
|
||||||
|
| `DATA_DIR` | `./data` | 运行时数据目录 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRC 字幕使用流程
|
||||||
|
|
||||||
|
进入管理面板的 **「LRC 字幕」** 标签页。
|
||||||
|
|
||||||
|
### 1. 导入 LRC
|
||||||
|
|
||||||
|
- 点击「导入 .lrc 文件」,或直接把 LRC 文本粘贴到文本框。
|
||||||
|
- 支持标准格式:`[mm:ss.xx]`、`[mm:ss.xxx]`、`[mm:ss]`,以及一行多个时间戳(`[00:12.00][00:45.00]副歌`)。
|
||||||
|
- 支持增强型逐字时间戳 `<00:01.00>`:配合「逐字点亮」开关,文字会按标签逐字/逐词点亮;没有增强标签的行整句显示。
|
||||||
|
- 自动识别 `[ti:]` `[ar:]` `[al:]` `[by:]` `[offset:]` 等元数据并单独展示。
|
||||||
|
|
||||||
|
### 2. 过滤版权信息
|
||||||
|
|
||||||
|
默认开启「过滤版权 / 制作信息行」,命中关键词(作词、作曲、编曲、制作人、出品、录音、混音、©、℗、lyrics by …)的行会被剔除,并在「已过滤行」里列出被剔除的内容和原因。
|
||||||
|
|
||||||
|
- 关键词可以在下拉框中自由增删,也可一键恢复默认。
|
||||||
|
- 关闭「过滤版权 / 制作信息行」可显示全部时间轴行。
|
||||||
|
- 可关闭「忽略无时间戳行」保留没有时间戳的行用于检查。
|
||||||
|
|
||||||
|
### 3. 自由选择范围
|
||||||
|
|
||||||
|
- **起始句 / 结束句**:从过滤后的歌词行中选择,显示原始 LRC 时间与歌词内容。
|
||||||
|
- 「全选」恢复整首。
|
||||||
|
- 选中的范围会即时计算「最终字幕 N 句 / 时长」。
|
||||||
|
- 改动 LRC 文本或过滤条件时,范围会自动重置为全部,避免索引错位。
|
||||||
|
|
||||||
|
### 4. 时间对齐
|
||||||
|
|
||||||
|
- **自动偏移**:打点开始后,把「起始句」当作 0 点,后续句子按 LRC 原始间隔出现。因此打点瞬间第一句立即显示,不需要手动对齐第一句。
|
||||||
|
- **手动偏移**:整体提前/延后(毫秒),正数 = 延后。LRC 文件自带的 `[offset:]` 也会自动生效(正数 = 提前)。
|
||||||
|
- **末句停留**:最后一句显示多久(默认 4000 ms)后自动隐藏。
|
||||||
|
- **首句延迟**:播放控制栏中的运行参数,打点后延迟 N 毫秒再开始整条时间轴(默认 0)。
|
||||||
|
|
||||||
|
### 5. 打点播放
|
||||||
|
|
||||||
|
在「LRC 字幕」页顶部点击 **▶ 打点开始**。
|
||||||
|
|
||||||
|
- 快捷键(焦点不在输入框时):
|
||||||
|
- `L`:打点开始
|
||||||
|
- `J`:暂停 / 继续
|
||||||
|
- `K`:停止
|
||||||
|
- 支持暂停、继续、停止;管理页会实时显示当前句、下一句和进度。
|
||||||
|
- 左侧预设列表中的「打点」按钮可直接用已保存的配置开始。
|
||||||
|
- 编辑中的修改**不需要先保存**也可以打点(使用当前编辑器配置);点击「保存」后才会持久化。
|
||||||
|
|
||||||
|
### 6. 字幕样式
|
||||||
|
|
||||||
|
内置字幕样式编辑器,全部按预设持久化:
|
||||||
|
|
||||||
|
- 位置(顶部/居中/底部)、水平对齐。
|
||||||
|
- 入场动画:淡入 / 上滑 / 缩放 / 模糊 / 弹跳 / **自定义(写 CSS)** / 无。
|
||||||
|
- **入场时长**(`enterDurationMs`):让模糊、缩放等入场动画放慢,默认 300ms,模糊入场一般 1200–1800ms 更舒服。
|
||||||
|
- **入场模糊半径**(`blurPx`):模糊入场与模糊出场共用的最大模糊半径,默认 10px。
|
||||||
|
- **入场后回缩**:入场动画播完后,文字在 `shrinkDurationMs` 内缓慢缩放到 `holdShrinkTo` 倍(1 = 不回缩)。例如 0.94 + 3000ms 就是「缓缓回缩」。控件里有「轻微回缩」快捷按钮。
|
||||||
|
- **自动适配单句时长**:入场时长 + 回缩时长会与「到下一句的间隔」自动协商。间隔不够时,入场最多占 45%,回缩占用剩余时间(至少 120ms),保证每句都能完整播完入场→回缩,不会出现「回缩刚开始就跳到下一句」。最后一句按「末句停留」计算。
|
||||||
|
- **出场动画**(`outro`):整段字幕结束时播放,可选 淡出 / 模糊消散 / 下滑淡出 / 上浮淡出 / 缩小淡出 / 自定义 / 无,配套 **出场时长**(`outDurationMs`,默认 260ms)。手动点「停止」也会走完整的出场动画。
|
||||||
|
- 字号、字重、字间距、行高、文字颜色。
|
||||||
|
- 字体:常用字体快捷选择 + 自定义 CSS `font-family`。注意 OBS 所在电脑需要安装对应字体,否则回退到系统字体。
|
||||||
|
- 背景:支持 `rgba()` / `transparent`,可用「显示背景」开关一键禁用(保留颜色配置)。
|
||||||
|
- 文字阴影:可编辑具体阴影,可用「文字阴影」开关一键禁用。
|
||||||
|
- 「显示下一句」开关:关闭后不再提前显示下一句提示。
|
||||||
|
- 「逐字点亮」开关 + 「未唱文字颜色」:增强型 LRC 逐字显示,唱到的字变为主色,未唱的字保持半透明;当前字额外带 `.is-current` 类可供自定义 CSS 使用。
|
||||||
|
- 一行多时间戳(副歌复用)或同一时间点多行(双语)会自动退回整句显示,避免逐字时间错位。
|
||||||
|
- 内边距、圆角、最大宽度、距画面边缘距离、下一句缩放/颜色。
|
||||||
|
- **自定义 CSS**:见下一节。
|
||||||
|
|
||||||
|
每条字幕的生命周期是三个阶段,可以用 CSS 钩子分别定制:
|
||||||
|
|
||||||
|
| 阶段 | 状态类 | 默认行为 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 入场 | `.lrc-state-entering` | 播放所选入场动画,时长 = `enterDurationMs` |
|
||||||
|
| 停留 | `.lrc-state-hold` | 保持可读,同时在 `shrinkDurationMs` 内回缩到 `holdShrinkTo` |
|
||||||
|
| 出场 | `.lrc-state-leaving` + `.lrc-out-*` | 播放所选出场动画,时长 = `outDurationMs`,结束后隐藏 |
|
||||||
|
|
||||||
|
右侧有 16:9 样式预览和「试播本段」,可直接看到入场 → 回缩 → 出场的完整时序;「循环」开着时会反复重播,方便调时长。
|
||||||
|
|
||||||
|
### 7. 自定义动画 / 修饰(CSS)
|
||||||
|
|
||||||
|
每个 LRC 预设都带一个「自定义 CSS / 自定义动画」输入框,内容会同时注入管理页预览和 OBS 浏览器源。可用的选择器:
|
||||||
|
|
||||||
|
| 选择器 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `.lrc-layer` | 整块字幕层(可用来做背景、发光、定位微调) |
|
||||||
|
| `.lrc-box` | 字幕盒(背景、边框、圆角、发光、滤镜) |
|
||||||
|
| `.lrc-text` | 当前句文字 |
|
||||||
|
| `.lrc-next` | 下一句提示 |
|
||||||
|
| `.lrc-word` | 逐字模式下的每个字/词 |
|
||||||
|
| `.lrc-word.is-pending` | 还没唱到的字 |
|
||||||
|
| `.lrc-word.is-sung` | 已经唱到的字 |
|
||||||
|
| `.lrc-word.is-current` | 当前正在唱的字(用于高亮/放大/发光) |
|
||||||
|
| `.lrc-anim-custom .lrc-text` | 选择「自定义」入场动画时的动画目标 |
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* 自定义弹跳入场:入场动画选择「自定义」 */
|
||||||
|
@keyframes myBounce {
|
||||||
|
0% { opacity: 0; transform: translateY(26px) scale(0.9); }
|
||||||
|
60% { opacity: 1; transform: translateY(-6px) scale(1.03); }
|
||||||
|
100% { opacity: 1; transform: translateY(0) scale(1); }
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-custom .lrc-text {
|
||||||
|
animation: myBounce 0.55s cubic-bezier(0.2, 0.9, 0.3, 1.2) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 逐字发光 */
|
||||||
|
.lrc-layer .lrc-word.is-sung {
|
||||||
|
text-shadow: 0 0 10px rgba(255, 209, 102, 0.95),
|
||||||
|
0 0 24px rgba(255, 92, 141, 0.55);
|
||||||
|
}
|
||||||
|
.lrc-layer .lrc-word.is-current {
|
||||||
|
color: #ffd166 !important;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 管理页提供「+ 霓虹发光」「+ 渐变文字」「+ 描边文字」「+ 逐字发光」「+ 弹跳入场」「+ 擦除入场」等一键片段。
|
||||||
|
- 背景、颜色、阴影等由内置控件写成内联样式,若要覆盖它们请使用 `!important`。
|
||||||
|
- 为了不影响管理页其他区域,建议所有选择器都以 `.lrc-layer` 开头;预览容器额外带有 `.lrc-preview-layer` 类,可写预览专用规则。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 持久化
|
||||||
|
|
||||||
|
运行时数据全部位于 `data/`(已被 `.gitignore` 忽略):
|
||||||
|
|
||||||
|
```
|
||||||
|
data/
|
||||||
|
├── appearance-presets.json # 外观预设(HTML 模板)
|
||||||
|
├── content-presets.json # 内容预设
|
||||||
|
├── lrc-presets.json # LRC 预设(LRC 原文、过滤条件、范围、样式)
|
||||||
|
└── settings.json # 全局设置(自动隐藏时长等)
|
||||||
|
```
|
||||||
|
|
||||||
|
设计要点:
|
||||||
|
|
||||||
|
- **首次启动自动生成**:如果文件不存在,用 `seed/` 中的示例数据初始化;之后不再覆盖。
|
||||||
|
- **原子写入**:先写临时文件再 `rename`,进程异常不会留下半截 JSON。
|
||||||
|
- **损坏自愈**:文件无法解析时备份为 `*.corrupt-<时间戳>.bak`,再用种子数据重建,不会导致服务起不来。
|
||||||
|
- **带 schemaVersion**:每个文件带版本号,便于后续迁移。
|
||||||
|
- **输入校验**:所有写入都会经过 `lib/lrc.js` / `lib/models.js` 的规整和范围限制。
|
||||||
|
- **源码不存业务数据**:示例库只放在 `seed/`,用户数据只放 `data/`。想恢复默认,停止服务后删除 `data/` 再启动即可。
|
||||||
|
|
||||||
|
如果要迁移/备份,直接复制 `data/` 目录即可。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API 概览
|
||||||
|
|
||||||
|
原有接口保持不变,新增 LRC 相关接口:
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/api/presets` | 全部外观/内容/LRC 预设 + 运行状态 |
|
||||||
|
| GET | `/api/lrc-presets` | LRC 预设列表 |
|
||||||
|
| POST | `/api/lrc-presets` | 新建 LRC 预设 |
|
||||||
|
| PUT | `/api/lrc-presets/:id` | 更新 LRC 预设 |
|
||||||
|
| DELETE | `/api/lrc-presets/:id` | 删除 LRC 预设(如正在播放会停止) |
|
||||||
|
| POST | `/api/lrc/parse` | 仅解析/预览:`{ source, filters, range, offsetMs, tailMs }` |
|
||||||
|
| POST | `/api/lrc-presets/:id/play` | 打点开始:`{ leadInMs, overrides }` |
|
||||||
|
| POST | `/api/lrc/pause` | 暂停 |
|
||||||
|
| POST | `/api/lrc/resume` | 继续 |
|
||||||
|
| POST | `/api/lrc/stop` | 停止 |
|
||||||
|
| GET | `/api/lrc/state` | 当前 LRC 播放状态 |
|
||||||
|
| GET | `/api/health` | 健康检查 |
|
||||||
|
|
||||||
|
WebSocket 消息:
|
||||||
|
|
||||||
|
- `activePreset`:下三分之一条的当前状态(与原版一致)。
|
||||||
|
- `lrcState`:LRC 播放状态(cues、锚点时间、暂停状态、样式)。
|
||||||
|
- `clock`:客户端时钟校准(管理页/OBS 与服务器时间对齐,保证字幕切换准确)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
server.js Express + WebSocket 服务、API
|
||||||
|
lib/
|
||||||
|
store.js 通用 JSON 持久化(原子写、损坏恢复、schemaVersion)
|
||||||
|
lrc.js LRC 解析、版权过滤、时间轴构建、预设校验
|
||||||
|
models.js 外观/内容预设与设置的校验
|
||||||
|
seed.js 首次启动种子数据加载
|
||||||
|
seed/
|
||||||
|
defaults.json 默认预设元数据
|
||||||
|
default-appearance.html
|
||||||
|
default.lrc
|
||||||
|
public/
|
||||||
|
manage.html 管理面板(React + antd)
|
||||||
|
widget.html OBS 浏览器源(下三分之一条 + LRC 字幕层)
|
||||||
|
lrc.css LRC 动画 / 逐字样式(管理页预览与 widget 共用)
|
||||||
|
admin.html 旧版管理页
|
||||||
|
tests/ 单元测试(LRC / 存储)
|
||||||
|
data/ 运行时数据(自动生成,不提交)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
覆盖 LRC 时间戳解析、元数据、版权过滤、范围/偏移、增强型逐字片段、双语同时间戳合并、样式开关、自定义 CSS、持久化写入/重载、损坏恢复等。
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
- 管理页与 OBS 浏览器源通过 WebSocket 实时同步;断线后都会自动重连并重新同步状态。
|
||||||
|
- 字幕播放的时间轴在服务器构建,OBS 端通过时钟校准在本地调度,网络抖动不会累积成音画不同步。
|
||||||
|
- 下三分之一条与 LRC 字幕是独立图层,可以同时显示;「清空显示」会同时隐藏两者。
|
||||||
+573
@@ -0,0 +1,573 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LRC 解析 / 过滤 / 时间轴构建。
|
||||||
|
*
|
||||||
|
* 纯函数模块,不依赖 express / fs,方便单元测试,也方便服务端和 API 复用。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const MAX_SOURCE_CHARS = 2_000_000;
|
||||||
|
const MAX_LINES = 5000;
|
||||||
|
|
||||||
|
/** 默认用于过滤版权 / 制作信息行的关键词(命中行首附近即视为制作信息) */
|
||||||
|
const DEFAULT_CREDIT_KEYWORDS = [
|
||||||
|
'作词', '作曲', '编曲', '词曲', '词:', '曲:', '制作人', '制作', '出品', '监制',
|
||||||
|
'录音', '混音', '母带', '发行', '版权', '策划', '统筹', '艺术总监', '和声',
|
||||||
|
'吉他', '贝斯', '鼓手', '弦乐', '录音师', '混音师', '母带师', '演唱', '原唱',
|
||||||
|
'歌词制作', '歌词编辑', '翻译', '校对', 'lrc制作', 'lrc编辑',
|
||||||
|
'lyrics by', 'composed by', 'written by', 'arranged by', 'produced by',
|
||||||
|
'mixed by', 'mastered by', 'copyright', 'all rights reserved', 'op:', 'sp:',
|
||||||
|
'℗', '©',
|
||||||
|
];
|
||||||
|
|
||||||
|
const LRC_POSITIONS = ['top', 'center', 'bottom'];
|
||||||
|
const LRC_ALIGNS = ['left', 'center', 'right'];
|
||||||
|
const LRC_ANIMATIONS = ['none', 'fade', 'slide', 'zoom', 'blur', 'bounce', 'custom'];
|
||||||
|
const LRC_OUTROS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
|
||||||
|
|
||||||
|
const DEFAULT_LRC_FILTERS = {
|
||||||
|
dropCreditLines: true,
|
||||||
|
// 是否丢弃没有时间戳的行(LRC 里通常是标题、版权、备注)
|
||||||
|
dropUntimed: true,
|
||||||
|
creditKeywords: DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_LRC_STYLE = {
|
||||||
|
position: 'bottom',
|
||||||
|
align: 'center',
|
||||||
|
fontFamily: "'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif",
|
||||||
|
fontSize: 42,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: '#ffffff',
|
||||||
|
letterSpacing: 1,
|
||||||
|
lineHeight: 1.35,
|
||||||
|
background: 'rgba(0, 0, 0, 0.55)',
|
||||||
|
backgroundEnabled: true,
|
||||||
|
paddingX: 28,
|
||||||
|
paddingY: 12,
|
||||||
|
borderRadius: 12,
|
||||||
|
maxWidthPercent: 86,
|
||||||
|
textShadow: '0 2px 12px rgba(0, 0, 0, 0.85)',
|
||||||
|
textShadowEnabled: true,
|
||||||
|
animation: 'fade',
|
||||||
|
// 入场时长(ms):模糊/缩放等动画跑得更久一些更适合直播画面
|
||||||
|
enterDurationMs: 300,
|
||||||
|
// 回缩:入场动画结束后,文字缓慢缩小到 holdShrinkTo 倍(1 = 不回缩)
|
||||||
|
holdShrinkTo: 1,
|
||||||
|
shrinkDurationMs: 0,
|
||||||
|
blurPx: 10,
|
||||||
|
// 出场:整段字幕结束时播放
|
||||||
|
outro: 'fade',
|
||||||
|
outDurationMs: 260,
|
||||||
|
// 自定义 CSS / 自定义动画:作用于 .lrc-layer / .lrc-box / .lrc-text / .lrc-word
|
||||||
|
customCss: '',
|
||||||
|
showNextLine: true,
|
||||||
|
nextLineColor: 'rgba(255, 255, 255, 0.55)',
|
||||||
|
nextLineScale: 0.68,
|
||||||
|
bottomOffsetVh: 7,
|
||||||
|
// 逐字:仅对含增强型 <mm:ss.xx> 标签的行生效
|
||||||
|
karaoke: true,
|
||||||
|
karaokePendingColor: 'rgba(255, 255, 255, 0.45)',
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_LRC_TIMING = {
|
||||||
|
offsetMs: 0,
|
||||||
|
tailMs: 4000,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── 解析 ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function normalizeSource(source) {
|
||||||
|
return String(source == null ? '' : source)
|
||||||
|
.slice(0, MAX_SOURCE_CHARS)
|
||||||
|
.replace(/^\uFEFF/, '')
|
||||||
|
.replace(/\r\n?/g, '\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把 "mm:ss.xx" / "mm:ss:xx" / "mm:ss" 解析成秒,失败返回 null */
|
||||||
|
function parseTimestamp(raw) {
|
||||||
|
const text = String(raw || '').trim();
|
||||||
|
const m = /^(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?$/.exec(text);
|
||||||
|
if (!m) return null;
|
||||||
|
const minutes = Number(m[1]);
|
||||||
|
const seconds = Number(m[2]);
|
||||||
|
if (!Number.isFinite(minutes) || !Number.isFinite(seconds) || seconds > 59) return null;
|
||||||
|
let fraction = 0;
|
||||||
|
if (m[3] !== undefined) {
|
||||||
|
fraction = Number(m[3]) / Math.pow(10, m[3].length);
|
||||||
|
}
|
||||||
|
return minutes * 60 + seconds + fraction;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanText(text) {
|
||||||
|
return text
|
||||||
|
.replace(/\u00a0/g, ' ')
|
||||||
|
.replace(/[ \t]+$/g, '')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析增强型逐字标签:<mm:ss.xx>文字
|
||||||
|
* 返回纯文本 + 逐字片段(片段 time 为 LRC 原始绝对时间,单位秒)。
|
||||||
|
* 没有增强标签时 segments 为 null。
|
||||||
|
*/
|
||||||
|
function extractEnhancedText(rest, fallbackTime) {
|
||||||
|
const tagRe = /<(\d{1,3}:\d{1,2}(?:[.:]\d{1,3})?)>/g;
|
||||||
|
const matches = [];
|
||||||
|
let match;
|
||||||
|
while ((match = tagRe.exec(rest)) !== null) {
|
||||||
|
const time = parseTimestamp(match[1]);
|
||||||
|
if (time !== null) matches.push({ start: match.index, end: tagRe.lastIndex, time });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matches.length) {
|
||||||
|
return { text: cleanText(rest), segments: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const segments = [];
|
||||||
|
let cursor = 0;
|
||||||
|
let currentTime = Number.isFinite(fallbackTime) ? fallbackTime : 0;
|
||||||
|
for (const tag of matches) {
|
||||||
|
const chunk = rest.slice(cursor, tag.start).replace(/\u00a0/g, ' ');
|
||||||
|
if (chunk) segments.push({ time: currentTime, text: chunk });
|
||||||
|
currentTime = tag.time;
|
||||||
|
cursor = tag.end;
|
||||||
|
}
|
||||||
|
const tail = rest.slice(cursor).replace(/\u00a0/g, ' ');
|
||||||
|
if (tail) segments.push({ time: currentTime, text: tail });
|
||||||
|
|
||||||
|
// 去掉整行首尾空白,但保留词与词之间的空格
|
||||||
|
if (segments.length) {
|
||||||
|
segments[0] = { ...segments[0], text: segments[0].text.replace(/^\s+/, '') };
|
||||||
|
const last = segments.length - 1;
|
||||||
|
segments[last] = { ...segments[last], text: segments[last].text.replace(/\s+$/, '') };
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleaned = segments.filter((segment) => segment.text);
|
||||||
|
const text = cleanText(cleaned.map((segment) => segment.text).join(''));
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
// 只有多段逐字时间轴才有意义
|
||||||
|
segments: cleaned.length >= 2 ? cleaned : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 LRC 文本。
|
||||||
|
* @param {string} source
|
||||||
|
* @returns {{
|
||||||
|
* meta: Record<string,string>, metaOffsetMs: number,
|
||||||
|
* lines: Array<any>, lyricEntries: Array<any>,
|
||||||
|
* warnings: string[], sourceLineCount: number
|
||||||
|
* }}
|
||||||
|
*/
|
||||||
|
function parseLrc(source) {
|
||||||
|
const text = normalizeSource(source);
|
||||||
|
const rawLines = text.split('\n');
|
||||||
|
const lines = [];
|
||||||
|
const lyricEntries = [];
|
||||||
|
const meta = {};
|
||||||
|
const warnings = [];
|
||||||
|
let consumedLines = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < rawLines.length; i += 1) {
|
||||||
|
if (consumedLines >= MAX_LINES) {
|
||||||
|
warnings.push(`歌词行数超过 ${MAX_LINES} 行,已截断`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
consumedLines += 1;
|
||||||
|
|
||||||
|
const raw = rawLines[i];
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
lines.push({ line: i + 1, raw, text: '', times: [], time: null, kind: 'blank' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const times = [];
|
||||||
|
const inlineMeta = [];
|
||||||
|
let rest = trimmed;
|
||||||
|
|
||||||
|
// 只解析行首连续的 [xx] 标签
|
||||||
|
const leading = /^((?:\[[^\[\]]*\])+)([\s\S]*)$/.exec(trimmed);
|
||||||
|
if (leading) {
|
||||||
|
rest = leading[2];
|
||||||
|
const tagRe = /\[([^\[\]]*)\]/g;
|
||||||
|
let tagMatch;
|
||||||
|
while ((tagMatch = tagRe.exec(leading[1])) !== null) {
|
||||||
|
const inner = tagMatch[1].trim();
|
||||||
|
const seconds = parseTimestamp(inner);
|
||||||
|
if (seconds !== null) {
|
||||||
|
times.push(seconds);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const metaMatch = /^([a-zA-Z][a-zA-Z0-9_#-]*)\s*:\s*([\s\S]*)$/.exec(inner);
|
||||||
|
if (metaMatch) {
|
||||||
|
inlineMeta.push({ key: metaMatch[1].toLowerCase(), value: metaMatch[2].trim() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const enhanced = extractEnhancedText(rest, times.length ? Math.min(...times) : 0);
|
||||||
|
const lyricText = enhanced.text;
|
||||||
|
|
||||||
|
for (const tag of inlineMeta) {
|
||||||
|
// 同名标签保留第一次出现的值(更符合直觉)
|
||||||
|
if (!(tag.key in meta)) meta[tag.key] = tag.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (times.length === 0) {
|
||||||
|
if (lyricText) {
|
||||||
|
lines.push({
|
||||||
|
line: i + 1, raw, text: lyricText, times: [], time: null,
|
||||||
|
kind: inlineMeta.length ? 'meta' : 'untimed',
|
||||||
|
});
|
||||||
|
} else if (inlineMeta.length) {
|
||||||
|
lines.push({
|
||||||
|
line: i + 1, raw, text: '', times: [], time: null,
|
||||||
|
kind: 'meta', meta: inlineMeta,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
lines.push({ line: i + 1, raw, text: '', times: [], time: null, kind: 'blank' });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const timesSorted = times.slice().sort((a, b) => a - b);
|
||||||
|
// 增强型逐字时间轴只对单时间戳歌词有效;一行多时间戳(副歌复用)无法对应,退回整句
|
||||||
|
const entrySegments = timesSorted.length === 1 ? enhanced.segments : null;
|
||||||
|
lines.push({
|
||||||
|
line: i + 1, raw, text: lyricText, times: timesSorted, time: timesSorted[0],
|
||||||
|
kind: lyricText ? 'lyric' : 'blank', segments: entrySegments,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (lyricText) {
|
||||||
|
for (const seconds of timesSorted) {
|
||||||
|
lyricEntries.push({
|
||||||
|
line: i + 1,
|
||||||
|
time: seconds,
|
||||||
|
text: lyricText,
|
||||||
|
segments: entrySegments,
|
||||||
|
raw,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lyricEntries.sort((a, b) => (a.time - b.time) || (a.line - b.line));
|
||||||
|
|
||||||
|
if (!lyricEntries.length) {
|
||||||
|
warnings.push('没有找到带时间戳的歌词行,请确认 LRC 格式是否正确');
|
||||||
|
}
|
||||||
|
|
||||||
|
let metaOffsetMs = 0;
|
||||||
|
if (meta.offset !== undefined) {
|
||||||
|
const parsedOffset = Number(String(meta.offset).replace(/[^\d.+-]/g, ''));
|
||||||
|
if (Number.isFinite(parsedOffset)) metaOffsetMs = Math.round(parsedOffset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
meta,
|
||||||
|
metaOffsetMs,
|
||||||
|
lines,
|
||||||
|
lyricEntries,
|
||||||
|
warnings,
|
||||||
|
sourceLineCount: consumedLines,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 过滤 ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function normalizeKeywordList(input) {
|
||||||
|
if (!Array.isArray(input)) return DEFAULT_CREDIT_KEYWORDS.slice();
|
||||||
|
const seen = new Set();
|
||||||
|
const result = [];
|
||||||
|
for (const item of input) {
|
||||||
|
const kw = String(item == null ? '' : item).trim();
|
||||||
|
if (!kw) continue;
|
||||||
|
const lower = kw.toLowerCase();
|
||||||
|
if (seen.has(lower)) continue;
|
||||||
|
seen.add(lower);
|
||||||
|
result.push(kw.slice(0, 40));
|
||||||
|
if (result.length >= 120) break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断一行歌词是否是版权 / 制作信息。
|
||||||
|
* 规则:出现 © / ℗,或配置的关键词出现在行首附近(允许少量标点前缀)。
|
||||||
|
*/
|
||||||
|
function isCreditLine(text, keywords) {
|
||||||
|
const value = String(text == null ? '' : text).trim();
|
||||||
|
if (!value) return false;
|
||||||
|
if (/[©℗]/.test(value)) return true;
|
||||||
|
|
||||||
|
const lower = value.toLowerCase();
|
||||||
|
const list = Array.isArray(keywords) ? keywords : DEFAULT_CREDIT_KEYWORDS;
|
||||||
|
for (const rawKeyword of list) {
|
||||||
|
const keyword = String(rawKeyword == null ? '' : rawKeyword).trim().toLowerCase();
|
||||||
|
if (!keyword) continue;
|
||||||
|
const idx = lower.indexOf(keyword);
|
||||||
|
if (idx === -1) continue;
|
||||||
|
if (idx <= 6) return true;
|
||||||
|
// 括号中的英文制作信息,例如 "Song (Prod. by XXX)"
|
||||||
|
if (/^[a-z]/.test(keyword) && idx <= 40) {
|
||||||
|
const prefix = lower.slice(Math.max(0, idx - 2), idx);
|
||||||
|
if (/[((\[【]/.test(prefix)) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRange(range) {
|
||||||
|
const input = range && typeof range === 'object' ? range : {};
|
||||||
|
const start = Number.isFinite(Number(input.startIndex)) ? Math.max(0, Math.floor(Number(input.startIndex))) : 0;
|
||||||
|
let end = null;
|
||||||
|
if (input.endIndex !== null && input.endIndex !== undefined && input.endIndex !== '') {
|
||||||
|
const parsed = Number(input.endIndex);
|
||||||
|
if (Number.isFinite(parsed)) end = Math.max(0, Math.floor(parsed));
|
||||||
|
}
|
||||||
|
if (end !== null && end < start) end = start;
|
||||||
|
return { startIndex: start, endIndex: end };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFilters(filters) {
|
||||||
|
const input = filters && typeof filters === 'object' ? filters : {};
|
||||||
|
return {
|
||||||
|
dropCreditLines: input.dropCreditLines !== false,
|
||||||
|
dropUntimed: input.dropUntimed !== false,
|
||||||
|
creditKeywords: normalizeKeywordList(
|
||||||
|
Array.isArray(input.creditKeywords) ? input.creditKeywords : DEFAULT_LRC_FILTERS.creditKeywords
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据过滤条件 + 范围构建最终字幕时间轴。
|
||||||
|
* 时间轴以「第一个入选句子」为 0 点,因此打点时第一句会立即出现(自动偏移)。
|
||||||
|
*/
|
||||||
|
function buildTimeline(parsed, options = {}) {
|
||||||
|
const filters = normalizeFilters(options.filters);
|
||||||
|
const range = normalizeRange(options.range);
|
||||||
|
const offsetMs = clampNumber(options.offsetMs, -60000, 60000, 0);
|
||||||
|
const tailMs = clampNumber(options.tailMs, 0, 60000, DEFAULT_LRC_TIMING.tailMs);
|
||||||
|
const metaOffsetMs = Number.isFinite(parsed.metaOffsetMs) ? parsed.metaOffsetMs : 0;
|
||||||
|
|
||||||
|
const keptCandidates = [];
|
||||||
|
const excluded = [];
|
||||||
|
const stats = {
|
||||||
|
sourceLines: parsed.sourceLineCount || parsed.lines.length,
|
||||||
|
timedLyricLines: parsed.lyricEntries.length,
|
||||||
|
excludedCredit: 0,
|
||||||
|
excludedUntimed: 0,
|
||||||
|
keptLyricLines: 0,
|
||||||
|
cueCount: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const entry of parsed.lyricEntries) {
|
||||||
|
if (filters.dropCreditLines && isCreditLine(entry.text, filters.creditKeywords)) {
|
||||||
|
stats.excludedCredit += 1;
|
||||||
|
excluded.push({ time: entry.time, text: entry.text, line: entry.line, reason: '版权/制作信息' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
keptCandidates.push(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filters.dropUntimed) {
|
||||||
|
for (const line of parsed.lines) {
|
||||||
|
if (line.kind !== 'untimed') continue;
|
||||||
|
stats.excludedUntimed += 1;
|
||||||
|
excluded.push({ time: null, text: line.text, line: line.line, reason: '无时间戳' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.keptLyricLines = keptCandidates.length;
|
||||||
|
const maxIndex = Math.max(0, keptCandidates.length - 1);
|
||||||
|
const startIndex = keptCandidates.length ? Math.min(range.startIndex, maxIndex) : 0;
|
||||||
|
const endIndex = keptCandidates.length
|
||||||
|
? Math.min(range.endIndex === null ? maxIndex : range.endIndex, maxIndex)
|
||||||
|
: 0;
|
||||||
|
const selected = keptCandidates.slice(startIndex, endIndex + 1);
|
||||||
|
|
||||||
|
const shiftMs = offsetMs - metaOffsetMs;
|
||||||
|
const firstTime = selected.length ? selected[0].time : 0;
|
||||||
|
const cueMap = new Map();
|
||||||
|
|
||||||
|
for (const entry of selected) {
|
||||||
|
const rawT = Math.round((entry.time - firstTime) * 1000) + shiftMs;
|
||||||
|
const t = Math.max(0, rawT);
|
||||||
|
const text = entry.text.trim();
|
||||||
|
if (!text) continue;
|
||||||
|
|
||||||
|
let segments = null;
|
||||||
|
if (Array.isArray(entry.segments) && entry.segments.length >= 2) {
|
||||||
|
segments = entry.segments
|
||||||
|
.map((segment) => ({
|
||||||
|
at: Math.max(0, Math.round((segment.time - firstTime) * 1000) + shiftMs),
|
||||||
|
text: segment.text,
|
||||||
|
}))
|
||||||
|
.filter((segment) => segment.text)
|
||||||
|
.sort((a, b) => a.at - b.at);
|
||||||
|
if (segments.length < 2) segments = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cueMap.has(t)) {
|
||||||
|
const existing = cueMap.get(t);
|
||||||
|
existing.text = `${existing.text}\n${text}`;
|
||||||
|
// 双语/多行合并后无法复用逐字时间轴,退回整句点亮
|
||||||
|
existing.segments = null;
|
||||||
|
} else {
|
||||||
|
cueMap.set(t, {
|
||||||
|
t,
|
||||||
|
text,
|
||||||
|
line: entry.line,
|
||||||
|
sourceTimeMs: Math.round(entry.time * 1000),
|
||||||
|
segments,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cues = Array.from(cueMap.values()).sort((a, b) => a.t - b.t).map((cue, index) => ({
|
||||||
|
...cue,
|
||||||
|
index,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const lastCue = cues[cues.length - 1] || null;
|
||||||
|
stats.cueCount = cues.length;
|
||||||
|
stats.karaokeCues = cues.filter((cue) => Array.isArray(cue.segments) && cue.segments.length >= 2).length;
|
||||||
|
|
||||||
|
const candidates = keptCandidates.map((entry, index) => ({
|
||||||
|
index,
|
||||||
|
time: entry.time,
|
||||||
|
text: entry.text,
|
||||||
|
line: entry.line,
|
||||||
|
inRange: index >= startIndex && index <= endIndex,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
cues,
|
||||||
|
candidates,
|
||||||
|
excluded,
|
||||||
|
stats,
|
||||||
|
range: { startIndex, endIndex: keptCandidates.length ? endIndex : null },
|
||||||
|
requestedRange: range,
|
||||||
|
offsetMs,
|
||||||
|
metaOffsetMs,
|
||||||
|
shiftMs,
|
||||||
|
tailMs,
|
||||||
|
firstSourceTimeMs: selected.length ? Math.round(firstTime * 1000) : null,
|
||||||
|
lastSourceTimeMs: lastCue ? lastCue.sourceTimeMs : null,
|
||||||
|
totalMs: lastCue ? lastCue.t : 0,
|
||||||
|
endMs: lastCue ? lastCue.t + tailMs : 0,
|
||||||
|
keptCount: keptCandidates.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampNumber(value, min, max, fallback) {
|
||||||
|
const n = Number(value);
|
||||||
|
if (!Number.isFinite(n)) return fallback;
|
||||||
|
return Math.min(max, Math.max(min, n));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 预设校验 ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function cleanString(value, maxLength) {
|
||||||
|
if (typeof value !== 'string') return '';
|
||||||
|
return value.slice(0, maxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeStyle(input) {
|
||||||
|
const src = input && typeof input === 'object' ? input : {};
|
||||||
|
const style = { ...DEFAULT_LRC_STYLE };
|
||||||
|
if (LRC_POSITIONS.includes(src.position)) style.position = src.position;
|
||||||
|
if (LRC_ALIGNS.includes(src.align)) style.align = src.align;
|
||||||
|
if (LRC_ANIMATIONS.includes(src.animation)) style.animation = src.animation;
|
||||||
|
if (LRC_OUTROS.includes(src.outro)) style.outro = src.outro;
|
||||||
|
if (typeof src.fontFamily === 'string' && src.fontFamily.trim()) {
|
||||||
|
style.fontFamily = cleanString(src.fontFamily, 200);
|
||||||
|
}
|
||||||
|
if (typeof src.color === 'string' && src.color.trim()) style.color = cleanString(src.color, 40);
|
||||||
|
if (typeof src.background === 'string') style.background = cleanString(src.background, 80);
|
||||||
|
if (typeof src.textShadow === 'string') style.textShadow = cleanString(src.textShadow, 160);
|
||||||
|
if (typeof src.nextLineColor === 'string') style.nextLineColor = cleanString(src.nextLineColor, 60);
|
||||||
|
if (typeof src.karaokePendingColor === 'string') style.karaokePendingColor = cleanString(src.karaokePendingColor, 60);
|
||||||
|
if (typeof src.customCss === 'string') style.customCss = cleanString(src.customCss, 50_000);
|
||||||
|
|
||||||
|
style.fontSize = clampNumber(src.fontSize, 12, 200, style.fontSize);
|
||||||
|
style.fontWeight = clampNumber(src.fontWeight, 100, 900, style.fontWeight);
|
||||||
|
style.letterSpacing = clampNumber(src.letterSpacing, -10, 40, style.letterSpacing);
|
||||||
|
style.lineHeight = clampNumber(src.lineHeight, 0.8, 3, style.lineHeight);
|
||||||
|
style.paddingX = clampNumber(src.paddingX, 0, 200, style.paddingX);
|
||||||
|
style.paddingY = clampNumber(src.paddingY, 0, 120, style.paddingY);
|
||||||
|
style.borderRadius = clampNumber(src.borderRadius, 0, 100, style.borderRadius);
|
||||||
|
style.maxWidthPercent = clampNumber(src.maxWidthPercent, 20, 100, style.maxWidthPercent);
|
||||||
|
style.nextLineScale = clampNumber(src.nextLineScale, 0.3, 1, style.nextLineScale);
|
||||||
|
style.bottomOffsetVh = clampNumber(src.bottomOffsetVh, 0, 45, style.bottomOffsetVh);
|
||||||
|
style.enterDurationMs = clampNumber(src.enterDurationMs, 0, 10000, style.enterDurationMs);
|
||||||
|
style.outDurationMs = clampNumber(src.outDurationMs, 0, 10000, style.outDurationMs);
|
||||||
|
style.shrinkDurationMs = clampNumber(src.shrinkDurationMs, 0, 20000, style.shrinkDurationMs);
|
||||||
|
style.holdShrinkTo = clampNumber(src.holdShrinkTo, 0.3, 1, style.holdShrinkTo);
|
||||||
|
style.blurPx = clampNumber(src.blurPx, 0, 60, style.blurPx);
|
||||||
|
style.showNextLine = src.showNextLine !== false;
|
||||||
|
style.backgroundEnabled = src.backgroundEnabled !== false;
|
||||||
|
style.textShadowEnabled = src.textShadowEnabled !== false;
|
||||||
|
style.karaoke = src.karaoke !== false;
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLrcPreset(input) {
|
||||||
|
const src = input && typeof input === 'object' ? input : {};
|
||||||
|
const id = String(src.id || '').trim();
|
||||||
|
if (!id) throw new Error('LRC 预设缺少 id');
|
||||||
|
|
||||||
|
const source = typeof src.source === 'string' ? cleanString(src.source, MAX_SOURCE_CHARS) : '';
|
||||||
|
const parsed = parseLrc(source);
|
||||||
|
const range = normalizeRange(src.range);
|
||||||
|
const maxIndex = Math.max(0, parsed.lyricEntries.length - 1);
|
||||||
|
if (parsed.lyricEntries.length) {
|
||||||
|
range.startIndex = Math.min(range.startIndex, maxIndex);
|
||||||
|
if (range.endIndex !== null) {
|
||||||
|
range.endIndex = Math.min(Math.max(range.endIndex, range.startIndex), maxIndex);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
range.startIndex = 0;
|
||||||
|
range.endIndex = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: cleanString(String(src.name || ''), 120).trim() || '未命名 LRC 字幕',
|
||||||
|
source,
|
||||||
|
filters: normalizeFilters(src.filters),
|
||||||
|
range,
|
||||||
|
offsetMs: clampNumber(src.offsetMs, -60000, 60000, DEFAULT_LRC_TIMING.offsetMs),
|
||||||
|
tailMs: clampNumber(src.tailMs, 0, 60000, DEFAULT_LRC_TIMING.tailMs),
|
||||||
|
style: normalizeStyle(src.style),
|
||||||
|
createdAt: src.createdAt || now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
DEFAULT_LRC_FILTERS,
|
||||||
|
DEFAULT_LRC_STYLE,
|
||||||
|
DEFAULT_LRC_TIMING,
|
||||||
|
LRC_POSITIONS,
|
||||||
|
LRC_ALIGNS,
|
||||||
|
LRC_ANIMATIONS,
|
||||||
|
LRC_OUTROS,
|
||||||
|
MAX_SOURCE_CHARS,
|
||||||
|
parseLrc,
|
||||||
|
parseTimestamp,
|
||||||
|
buildTimeline,
|
||||||
|
isCreditLine,
|
||||||
|
normalizeFilters,
|
||||||
|
normalizeRange,
|
||||||
|
normalizeStyle,
|
||||||
|
normalizeLrcPreset,
|
||||||
|
normalizeKeywordList,
|
||||||
|
clampNumber,
|
||||||
|
};
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外观预设 / 内容预设 / 设置的校验与规整。
|
||||||
|
* 保持与旧版 API 字段兼容,同时对长度、枚举、类型做约束。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const LRC_STYLE_DEFAULTS = require('./lrc').DEFAULT_LRC_STYLE;
|
||||||
|
|
||||||
|
const ALIGNS = ['left', 'center', 'right'];
|
||||||
|
|
||||||
|
function str(value, maxLength) {
|
||||||
|
if (typeof value !== 'string') return '';
|
||||||
|
return value.slice(0, maxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
function idOf(input) {
|
||||||
|
const id = String(input && input.id != null ? input.id : '').trim();
|
||||||
|
if (!id) throw new Error('缺少 id');
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFieldDefs(input) {
|
||||||
|
if (!Array.isArray(input)) return [];
|
||||||
|
const seen = new Set();
|
||||||
|
const result = [];
|
||||||
|
for (const raw of input) {
|
||||||
|
if (!raw || typeof raw !== 'object') continue;
|
||||||
|
const key = str(raw.key, 64).trim();
|
||||||
|
if (!key || !/^[\w-]+$/.test(key) || seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
result.push({
|
||||||
|
key,
|
||||||
|
label: str(raw.label, 80).trim() || key,
|
||||||
|
defaultValue: str(raw.defaultValue, 2000),
|
||||||
|
});
|
||||||
|
if (result.length >= 40) break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeAppearancePreset(input) {
|
||||||
|
const src = input && typeof input === 'object' ? input : {};
|
||||||
|
const align = ALIGNS.includes(src.align) ? src.align : 'right';
|
||||||
|
return {
|
||||||
|
id: idOf(src),
|
||||||
|
name: str(src.name, 120).trim() || '未命名外观',
|
||||||
|
kind: 'iframe',
|
||||||
|
align,
|
||||||
|
themeColor: str(src.themeColor, 40),
|
||||||
|
extraCss: str(src.extraCss, 200_000),
|
||||||
|
fieldDefs: normalizeFieldDefs(src.fieldDefs),
|
||||||
|
html: str(src.html, 1_000_000),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeContentPreset(input) {
|
||||||
|
const src = input && typeof input === 'object' ? input : {};
|
||||||
|
const fields = {};
|
||||||
|
if (src.fields && typeof src.fields === 'object' && !Array.isArray(src.fields)) {
|
||||||
|
let count = 0;
|
||||||
|
for (const [key, value] of Object.entries(src.fields)) {
|
||||||
|
if (!/^[\w-]+$/.test(key)) continue;
|
||||||
|
fields[key] = str(typeof value === 'string' ? value : String(value == null ? '' : value), 20_000);
|
||||||
|
count += 1;
|
||||||
|
if (count >= 80) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: idOf(src),
|
||||||
|
name: str(src.name, 120).trim() || '未命名内容',
|
||||||
|
appearancePresetId: str(src.appearancePresetId, 120),
|
||||||
|
fields,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSettings(input) {
|
||||||
|
const src = input && typeof input === 'object' ? input : {};
|
||||||
|
const duration = Number(src.autoHideDuration);
|
||||||
|
return {
|
||||||
|
autoHideDuration: Number.isFinite(duration) ? Math.max(0, Math.min(600_000, Math.round(duration))) : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
ALIGNS,
|
||||||
|
LRC_STYLE_DEFAULTS,
|
||||||
|
normalizeAppearancePreset,
|
||||||
|
normalizeContentPreset,
|
||||||
|
normalizeSettings,
|
||||||
|
};
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 首次启动时使用的种子数据。
|
||||||
|
*
|
||||||
|
* 种子内容放在 seed/ 目录(HTML / LRC 用独立文件),
|
||||||
|
* 运行时数据写入 data/,两者分离,不会把用户数据写进源码。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { DEFAULT_CREDIT_KEYWORDS } = require('./lrc');
|
||||||
|
const { normalizeSettings } = require('./models');
|
||||||
|
|
||||||
|
const SEED_DIR = path.join(__dirname, '..', 'seed');
|
||||||
|
|
||||||
|
function readSeedFile(name) {
|
||||||
|
if (!name) return '';
|
||||||
|
try {
|
||||||
|
return fs.readFileSync(path.join(SEED_DIR, name), 'utf8');
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[seed] 无法读取种子文件 ${name}: ${err.message}`);
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadSeed() {
|
||||||
|
let raw = {};
|
||||||
|
try {
|
||||||
|
raw = JSON.parse(readSeedFile('defaults.json') || '{}');
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[seed] defaults.json 解析失败: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const appearancePresets = (Array.isArray(raw.appearancePresets) ? raw.appearancePresets : []).map((preset) => ({
|
||||||
|
...preset,
|
||||||
|
html: readSeedFile(preset.htmlFile),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const contentPresets = Array.isArray(raw.contentPresets) ? raw.contentPresets : [];
|
||||||
|
|
||||||
|
const lrcPresets = (Array.isArray(raw.lrcPresets) ? raw.lrcPresets : []).map((preset) => ({
|
||||||
|
...preset,
|
||||||
|
source: readSeedFile(preset.sourceFile),
|
||||||
|
filters: {
|
||||||
|
dropCreditLines: true,
|
||||||
|
dropUntimed: true,
|
||||||
|
creditKeywords: DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
...(preset.filters || {}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
appearancePresets,
|
||||||
|
contentPresets,
|
||||||
|
lrcPresets,
|
||||||
|
settings: normalizeSettings(raw.settings),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { loadSeed, SEED_DIR };
|
||||||
+213
@@ -0,0 +1,213 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量 JSON 持久化存储。
|
||||||
|
*
|
||||||
|
* - 所有运行时数据都保存在 data/ 目录(可通过 DATA_DIR 环境变量覆盖),
|
||||||
|
* 不会写死在源代码里。
|
||||||
|
* - 写入使用「临时文件 + rename」的原子方式,避免进程中断留下半个 JSON。
|
||||||
|
* - 文件损坏时自动备份为 *.corrupt-<时间戳>.bak 并使用种子数据重建。
|
||||||
|
* - 每个文件带有 schemaVersion,方便以后做数据迁移。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { randomUUID } = require('crypto');
|
||||||
|
|
||||||
|
const SCHEMA_VERSION = 1;
|
||||||
|
|
||||||
|
function nowIso() {
|
||||||
|
return new Date().toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clone(value) {
|
||||||
|
return JSON.parse(JSON.stringify(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function atomicWriteJson(filePath, value) {
|
||||||
|
const dir = path.dirname(filePath);
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
const text = JSON.stringify(value, null, 2) + '\n';
|
||||||
|
const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
||||||
|
fs.writeFileSync(tmp, text, 'utf8');
|
||||||
|
try {
|
||||||
|
fs.renameSync(tmp, filePath);
|
||||||
|
} catch (err) {
|
||||||
|
try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function backupCorrupt(filePath) {
|
||||||
|
try {
|
||||||
|
const backup = `${filePath}.corrupt-${Date.now()}.bak`;
|
||||||
|
fs.copyFileSync(filePath, backup);
|
||||||
|
console.error(`[store] ${path.basename(filePath)} 无法解析,已备份到 ${path.basename(backup)}`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[store] 备份损坏文件失败: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJsonFile(filePath) {
|
||||||
|
const raw = fs.readFileSync(filePath, 'utf8');
|
||||||
|
return JSON.parse(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 通用 JSON 文档(对象) */
|
||||||
|
class JsonDocument {
|
||||||
|
constructor(filePath, defaultValue) {
|
||||||
|
this.filePath = filePath;
|
||||||
|
this.defaultValue = clone(defaultValue);
|
||||||
|
this.value = clone(defaultValue);
|
||||||
|
this.loaded = false;
|
||||||
|
this.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
load() {
|
||||||
|
try {
|
||||||
|
const parsed = readJsonFile(this.filePath);
|
||||||
|
if (parsed && typeof parsed === 'object' && parsed.data && typeof parsed.data === 'object') {
|
||||||
|
this.value = { ...clone(this.defaultValue), ...parsed.data };
|
||||||
|
} else if (parsed && typeof parsed === 'object') {
|
||||||
|
this.value = { ...clone(this.defaultValue), ...parsed };
|
||||||
|
}
|
||||||
|
this.loaded = true;
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
||||||
|
this.value = clone(this.defaultValue);
|
||||||
|
this.loaded = false;
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
save() {
|
||||||
|
atomicWriteJson(this.filePath, {
|
||||||
|
schemaVersion: SCHEMA_VERSION,
|
||||||
|
updatedAt: nowIso(),
|
||||||
|
data: this.value,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
update(patch) {
|
||||||
|
this.value = { ...this.value, ...patch };
|
||||||
|
this.save();
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 通用 JSON 集合(数组) */
|
||||||
|
class JsonCollection {
|
||||||
|
/**
|
||||||
|
* @param {string} filePath
|
||||||
|
* @param {{ seed?: any[], normalize?: (item:any)=>any, idPrefix?: string }} options
|
||||||
|
*/
|
||||||
|
constructor(filePath, options = {}) {
|
||||||
|
this.filePath = filePath;
|
||||||
|
this.seed = clone(options.seed || []);
|
||||||
|
this.normalize = options.normalize || ((item) => item);
|
||||||
|
this.items = [];
|
||||||
|
this.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
load() {
|
||||||
|
try {
|
||||||
|
const parsed = readJsonFile(this.filePath);
|
||||||
|
const rawItems = Array.isArray(parsed) ? parsed : (Array.isArray(parsed.items) ? parsed.items : null);
|
||||||
|
if (!rawItems) throw new Error('数据格式不是数组');
|
||||||
|
this.items = rawItems.map((item) => this.safeNormalize(item)).filter(Boolean);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
||||||
|
this.items = this.seed.map((item) => this.safeNormalize(item)).filter(Boolean);
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
safeNormalize(item) {
|
||||||
|
try {
|
||||||
|
return this.normalize(item);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[store] 忽略无效数据 (${path.basename(this.filePath)}): ${err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
save() {
|
||||||
|
atomicWriteJson(this.filePath, {
|
||||||
|
schemaVersion: SCHEMA_VERSION,
|
||||||
|
updatedAt: nowIso(),
|
||||||
|
items: this.items,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
list() {
|
||||||
|
return this.items;
|
||||||
|
}
|
||||||
|
|
||||||
|
find(id) {
|
||||||
|
return this.items.find((item) => item.id === id) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
insert(item) {
|
||||||
|
const created = this.safeNormalize({ ...item, id: item.id || this.newId() });
|
||||||
|
if (!created) throw new Error('数据校验失败');
|
||||||
|
this.items.push(created);
|
||||||
|
this.save();
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id, patch) {
|
||||||
|
const idx = this.items.findIndex((item) => item.id === id);
|
||||||
|
if (idx === -1) return null;
|
||||||
|
const merged = this.safeNormalize({ ...this.items[idx], ...patch, id });
|
||||||
|
if (!merged) throw new Error('数据校验失败');
|
||||||
|
this.items[idx] = merged;
|
||||||
|
this.save();
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
remove(id) {
|
||||||
|
const before = this.items.length;
|
||||||
|
this.items = this.items.filter((item) => item.id !== id);
|
||||||
|
if (this.items.length === before) return false;
|
||||||
|
this.save();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
newId() {
|
||||||
|
return `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化全部存储。
|
||||||
|
* @param {string} dataDir
|
||||||
|
* @param {{ appearancePresets: any[], contentPresets: any[], lrcPresets: any[], settings: any }} seed
|
||||||
|
*/
|
||||||
|
function createStores(dataDir, seed) {
|
||||||
|
fs.mkdirSync(dataDir, { recursive: true });
|
||||||
|
return {
|
||||||
|
dataDir,
|
||||||
|
appearancePresets: new JsonCollection(path.join(dataDir, 'appearance-presets.json'), {
|
||||||
|
seed: seed.appearancePresets,
|
||||||
|
normalize: seed.normalizeAppearancePreset,
|
||||||
|
}),
|
||||||
|
contentPresets: new JsonCollection(path.join(dataDir, 'content-presets.json'), {
|
||||||
|
seed: seed.contentPresets,
|
||||||
|
normalize: seed.normalizeContentPreset,
|
||||||
|
}),
|
||||||
|
lrcPresets: new JsonCollection(path.join(dataDir, 'lrc-presets.json'), {
|
||||||
|
seed: seed.lrcPresets,
|
||||||
|
normalize: seed.normalizeLrcPreset,
|
||||||
|
}),
|
||||||
|
settings: new JsonDocument(path.join(dataDir, 'settings.json'), seed.settings),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
SCHEMA_VERSION,
|
||||||
|
JsonDocument,
|
||||||
|
JsonCollection,
|
||||||
|
createStores,
|
||||||
|
atomicWriteJson,
|
||||||
|
readJsonFile,
|
||||||
|
};
|
||||||
+2
-2
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "obs-lowerthird",
|
"name": "obs-lowerthird",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "OBS 下三分之一条与 LRC 字幕管理系统(JSON 持久化)",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"No tests configured\"",
|
"test": "node --test",
|
||||||
"start": "node server.js"
|
"start": "node server.js"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
|
|||||||
+2
-1
@@ -91,8 +91,9 @@
|
|||||||
<body>
|
<body>
|
||||||
<div style="background:rgba(24,144,255,0.12);border:1px solid rgba(24,144,255,0.3);border-radius:10px;padding:10px 14px;margin-bottom:16px;">
|
<div style="background:rgba(24,144,255,0.12);border:1px solid rgba(24,144,255,0.3);border-radius:10px;padding:10px 14px;margin-bottom:16px;">
|
||||||
<strong style="color:#40a9ff;">✨ 新版管理界面已上线!</strong>
|
<strong style="color:#40a9ff;">✨ 新版管理界面已上线!</strong>
|
||||||
<span style="color:#a0a4b3;font-size:13px;margin-left:8px;">支持内容/外观预设分离、占位符、键盘快捷键、自动隐藏等功能。</span>
|
<span style="color:#a0a4b3;font-size:13px;margin-left:8px;">支持内容/外观预设分离、LRC 字幕、打点播放、占位符、键盘快捷键、自动隐藏等功能。</span>
|
||||||
<a href="/manage.html" style="display:inline-block;margin-left:12px;padding:3px 12px;background:rgba(24,144,255,0.2);border:1px solid rgba(24,144,255,0.5);border-radius:6px;color:#40a9ff;text-decoration:none;font-size:13px;">→ 前往新版管理页</a>
|
<a href="/manage.html" style="display:inline-block;margin-left:12px;padding:3px 12px;background:rgba(24,144,255,0.2);border:1px solid rgba(24,144,255,0.5);border-radius:6px;color:#40a9ff;text-decoration:none;font-size:13px;">→ 前往新版管理页</a>
|
||||||
|
<a href="/manage.html#lrc" style="display:inline-block;margin-left:8px;padding:3px 12px;background:rgba(82,196,26,0.15);border:1px solid rgba(82,196,26,0.45);border-radius:6px;color:#73d13d;text-decoration:none;font-size:13px;">LRC 字幕</a>
|
||||||
</div>
|
</div>
|
||||||
<h1>OBS 节目信息下三分之一条 - 预设管理</h1>
|
<h1>OBS 节目信息下三分之一条 - 预设管理</h1>
|
||||||
<p>1. 在 OBS 中添加 Browser Source,URL 指向 <code>http://本机或服务器/widget.html</code><br>
|
<p>1. 在 OBS 中添加 Browser Source,URL 指向 <code>http://本机或服务器/widget.html</code><br>
|
||||||
|
|||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
/* LRC 字幕运行时样式:管理页预览与 OBS widget 共用
|
||||||
|
*
|
||||||
|
* 状态类统一挂在 .lrc-layer 上(lrc-state-entering / hold / leaving),
|
||||||
|
* 动画目标统一是 .lrc-text,两者之间隔着 .lrc-box,所以用后代选择器。
|
||||||
|
*
|
||||||
|
* 时间参数由页面通过 CSS 变量注入(带兜底默认值):
|
||||||
|
* --lrc-in-dur 入场时长(ms)
|
||||||
|
* --lrc-out-dur 出场时长(ms)
|
||||||
|
* --lrc-shrink-dur 入场结束后的缓慢回缩时长(ms)
|
||||||
|
* --lrc-shrink-to 回缩后的缩放比例(1 = 不回缩)
|
||||||
|
* --lrc-blur-px 模糊入场/出场时的最大模糊半径(px)
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* ── 入场:状态类驱动,时长可调 ─────────────────────────────────────────── */
|
||||||
|
.lrc-layer.lrc-state-entering .lrc-text {
|
||||||
|
animation-duration: var(--lrc-in-dur, 300ms);
|
||||||
|
animation-timing-function: ease;
|
||||||
|
animation-fill-mode: both;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-fade.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: lrcFadeIn;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-slide.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: lrcSlideIn;
|
||||||
|
animation-timing-function: cubic-bezier(0.2, 0.8, 0.3, 1);
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-zoom.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: lrcZoomIn;
|
||||||
|
animation-timing-function: cubic-bezier(0.2, 0.9, 0.3, 1.15);
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-blur.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: lrcBlurIn;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-anim-bounce.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: lrcBounceIn;
|
||||||
|
animation-timing-function: cubic-bezier(0.2, 0.9, 0.3, 1.2);
|
||||||
|
}
|
||||||
|
/* lrc-anim-custom:不内置动画,由「自定义 CSS」定义,例如:
|
||||||
|
.lrc-layer.lrc-anim-custom.lrc-state-entering .lrc-text { animation: myAnim .5s ease both; }
|
||||||
|
@keyframes myAnim { from { opacity: 0; transform: translateY(18px) scale(.96); } }
|
||||||
|
*/
|
||||||
|
.lrc-layer.lrc-anim-none.lrc-state-entering .lrc-text,
|
||||||
|
.lrc-layer.lrc-anim-custom.lrc-state-entering .lrc-text {
|
||||||
|
animation-name: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 入场结束后:缓慢回缩(scale 走 transform,不干扰逐字的颜色/发光) */
|
||||||
|
.lrc-layer.lrc-state-hold .lrc-text {
|
||||||
|
transform: scale(var(--lrc-shrink-to, 1));
|
||||||
|
transform-origin: center;
|
||||||
|
transition: transform var(--lrc-shrink-dur, 0ms) linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 出场 ───────────────────────────────────────────────────────────────── */
|
||||||
|
.lrc-layer.lrc-state-leaving .lrc-text {
|
||||||
|
animation-duration: var(--lrc-out-dur, 260ms);
|
||||||
|
animation-timing-function: ease;
|
||||||
|
animation-fill-mode: both;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-out-fade.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: lrcOutFade;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-out-slideDown.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: lrcOutSlideDown;
|
||||||
|
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-out-slideUp.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: lrcOutSlideUp;
|
||||||
|
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-out-zoom.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: lrcOutZoom;
|
||||||
|
}
|
||||||
|
.lrc-layer.lrc-out-blur.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: lrcOutBlur;
|
||||||
|
}
|
||||||
|
/* lrc-out-custom:由「自定义 CSS」定义出场动画 */
|
||||||
|
.lrc-layer.lrc-out-none.lrc-state-leaving .lrc-text,
|
||||||
|
.lrc-layer.lrc-out-custom.lrc-state-leaving .lrc-text {
|
||||||
|
animation-name: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 关键帧 ─────────────────────────────────────────────────────────────── */
|
||||||
|
@keyframes lrcFadeIn {
|
||||||
|
from { opacity: 0; }
|
||||||
|
to { opacity: 1; }
|
||||||
|
}
|
||||||
|
@keyframes lrcSlideIn {
|
||||||
|
from { opacity: 0; transform: translateY(12px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
|
@keyframes lrcZoomIn {
|
||||||
|
from { opacity: 0; transform: scale(0.9); }
|
||||||
|
to { opacity: 1; transform: scale(1); }
|
||||||
|
}
|
||||||
|
@keyframes lrcBlurIn {
|
||||||
|
0% { opacity: 0; filter: blur(var(--lrc-blur-px, 10px)); }
|
||||||
|
30% { opacity: 0.32; }
|
||||||
|
45% { opacity: 0.55; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.55)); }
|
||||||
|
100% { opacity: 1; filter: blur(0px); }
|
||||||
|
}
|
||||||
|
@keyframes lrcBounceIn {
|
||||||
|
0% { opacity: 0; transform: translateY(22px) scale(0.94); }
|
||||||
|
55% { opacity: 1; transform: translateY(-4px) scale(1.02); }
|
||||||
|
100% { opacity: 1; transform: translateY(0) scale(1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes lrcOutFade {
|
||||||
|
from { opacity: 1; }
|
||||||
|
to { opacity: 0; }
|
||||||
|
}
|
||||||
|
@keyframes lrcOutSlideDown {
|
||||||
|
from { opacity: 1; transform: translateY(0); }
|
||||||
|
to { opacity: 0; transform: translateY(14px); }
|
||||||
|
}
|
||||||
|
@keyframes lrcOutSlideUp {
|
||||||
|
from { opacity: 1; transform: translateY(0); }
|
||||||
|
to { opacity: 0; transform: translateY(-12px); }
|
||||||
|
}
|
||||||
|
@keyframes lrcOutZoom {
|
||||||
|
from { opacity: 1; transform: scale(1); }
|
||||||
|
to { opacity: 0; transform: scale(0.92); }
|
||||||
|
}
|
||||||
|
@keyframes lrcOutBlur {
|
||||||
|
0% { opacity: 1; filter: blur(0px); }
|
||||||
|
/* 一开始就快速起糊,避免前段看起来「没动静」 */
|
||||||
|
25% { opacity: 0.92; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.35)); }
|
||||||
|
60% { opacity: 0.55; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.72)); }
|
||||||
|
100% { opacity: 0; filter: blur(var(--lrc-blur-px, 10px)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 系统开启「减少动态效果」时收窄过渡,避免不适 */
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.lrc-layer.lrc-state-hold .lrc-text { transition-duration: 1ms; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 逐字(增强型 LRC) ─────────────────────────────────────────────────── */
|
||||||
|
.lrc-text .lrc-word {
|
||||||
|
color: var(--lrc-karaoke-pending, rgba(255, 255, 255, 0.45));
|
||||||
|
transition: color 0.12s linear, text-shadow 0.12s linear, opacity 0.12s linear;
|
||||||
|
}
|
||||||
|
.lrc-text .lrc-word.is-sung {
|
||||||
|
color: var(--lrc-color, #ffffff);
|
||||||
|
}
|
||||||
|
/* .is-current 是当前正在唱的字,可被自定义 CSS 用来做发光/放大等修饰 */
|
||||||
|
.lrc-text .lrc-word.is-current {
|
||||||
|
/* 默认与已唱字一致,仅作为自定义钩子 */
|
||||||
|
}
|
||||||
+1412
-11
File diff suppressed because it is too large.
Load diff
+523
-21
@@ -1,7 +1,9 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" href="data:," />
|
||||||
|
<link rel="stylesheet" href="/lrc.css" />
|
||||||
<title>OBS Lower Third Widget</title>
|
<title>OBS Lower Third Widget</title>
|
||||||
<style>
|
<style>
|
||||||
html, body {
|
html, body {
|
||||||
@@ -13,6 +15,8 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── 下三分之一条(原有功能) ─────────────────────────────── */
|
||||||
.lt-root {
|
.lt-root {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
@@ -37,16 +41,13 @@
|
|||||||
0 20px 40px rgba(0, 0, 0, 0.8),
|
0 20px 40px rgba(0, 0, 0, 0.8),
|
||||||
0 0 60px rgba(255, 140, 0, 0.45);
|
0 0 60px rgba(255, 140, 0, 0.45);
|
||||||
backdrop-filter: blur(18px);
|
backdrop-filter: blur(18px);
|
||||||
|
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
mask-image: radial-gradient(circle at 0 0, rgba(0,0,0,0.0), rgba(0,0,0,1) 45%),
|
|
||||||
}
|
}
|
||||||
.lt-container::before {
|
.lt-container::before {
|
||||||
content: '';
|
content: '';
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: -40%;
|
inset: -40%;
|
||||||
background-image: url('bg.png');
|
background-image: url('bg.png');
|
||||||
|
|
||||||
opacity: 0.85;
|
opacity: 0.85;
|
||||||
mix-blend-mode: screen;
|
mix-blend-mode: screen;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
@@ -106,20 +107,81 @@
|
|||||||
opacity: 0.95;
|
opacity: 0.95;
|
||||||
line-height: 1.45;
|
line-height: 1.45;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── LRC 字幕层 ──────────────────────────────────────────── */
|
||||||
|
.lrc-layer {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
z-index: 30;
|
||||||
|
pointer-events: none;
|
||||||
|
padding: 6vh 4vw;
|
||||||
|
box-sizing: border-box;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.22s ease;
|
||||||
|
}
|
||||||
|
.lrc-layer.visible { opacity: 1; }
|
||||||
|
.lrc-layer.pos-top { align-items: flex-start; justify-content: center; }
|
||||||
|
.lrc-layer.pos-center { align-items: center; justify-content: center; }
|
||||||
|
.lrc-layer.pos-bottom { align-items: flex-end; justify-content: center; }
|
||||||
|
|
||||||
|
.lrc-align-left { justify-content: flex-start !important; }
|
||||||
|
.lrc-align-center { justify-content: center !important; }
|
||||||
|
.lrc-align-right { justify-content: flex-end !important; }
|
||||||
|
|
||||||
|
.lrc-box {
|
||||||
|
display: inline-block;
|
||||||
|
box-sizing: border-box;
|
||||||
|
text-align: center;
|
||||||
|
max-width: 86%;
|
||||||
|
transition: transform 0.2s ease;
|
||||||
|
}
|
||||||
|
.lrc-text {
|
||||||
|
white-space: pre-line;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.lrc-next {
|
||||||
|
white-space: pre-line;
|
||||||
|
word-break: break-word;
|
||||||
|
margin-top: 0.35em;
|
||||||
|
}
|
||||||
|
.lrc-next:empty { display: none; }
|
||||||
|
|
||||||
|
.lrc-debug {
|
||||||
|
position: fixed;
|
||||||
|
top: 8px;
|
||||||
|
left: 8px;
|
||||||
|
z-index: 50;
|
||||||
|
color: rgba(255,255,255,0.6);
|
||||||
|
font: 11px/1.4 monospace;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<!-- 下三分之一条 -->
|
||||||
<div class="lt-root">
|
<div class="lt-root">
|
||||||
<div id="lt" class="lt-container">
|
<div id="lt" class="lt-container">
|
||||||
<div class="lt-container-inner" id="ltInner">
|
<div class="lt-container-inner" id="ltInner">
|
||||||
<img src="/zi.png">
|
<img src="/zi.png" alt="" />
|
||||||
<div class="lt-title" id="ltTitle"></div>
|
<div class="lt-title" id="ltTitle"></div>
|
||||||
<div class="lt-subtitle" id="ltSubtitle"></div>
|
<div class="lt-subtitle" id="ltSubtitle"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- LRC 字幕 -->
|
||||||
|
<div id="lrcLayer" class="lrc-layer pos-bottom lrc-align-center lrc-anim-fade">
|
||||||
|
<div id="lrcBox" class="lrc-box">
|
||||||
|
<div id="lrcText" class="lrc-text"></div>
|
||||||
|
<div id="lrcNext" class="lrc-next"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// ── 下三分之一条 ──────────────────────────────────────────
|
||||||
const lt = document.getElementById('lt');
|
const lt = document.getElementById('lt');
|
||||||
const ltInner = document.getElementById('ltInner');
|
const ltInner = document.getElementById('ltInner');
|
||||||
const titleEl = document.getElementById('ltTitle');
|
const titleEl = document.getElementById('ltTitle');
|
||||||
@@ -127,11 +189,12 @@
|
|||||||
let iframeEl = null;
|
let iframeEl = null;
|
||||||
let autoHideTimer = null;
|
let autoHideTimer = null;
|
||||||
|
|
||||||
// Replace {{key}} placeholders in html string with values from contentData
|
|
||||||
function fillPlaceholders(html, contentData) {
|
function fillPlaceholders(html, contentData) {
|
||||||
if (!html || !contentData) return html || '';
|
if (!html || !contentData) return html || '';
|
||||||
return html.replace(/\{\{(\w+)\}\}/g, (match, key) => {
|
return html.replace(/\{\{(\w+)\}\}/g, (match, key) => {
|
||||||
return key in contentData ? String(contentData[key]) : match;
|
return Object.prototype.hasOwnProperty.call(contentData, key)
|
||||||
|
? String(contentData[key])
|
||||||
|
: match;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +219,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function applyPreset(preset, contentData, autoHideDuration) {
|
function applyPreset(preset, contentData, autoHideDuration) {
|
||||||
// Clear any pending auto-hide timer
|
|
||||||
if (autoHideTimer) {
|
if (autoHideTimer) {
|
||||||
clearTimeout(autoHideTimer);
|
clearTimeout(autoHideTimer);
|
||||||
autoHideTimer = null;
|
autoHideTimer = null;
|
||||||
@@ -188,9 +250,8 @@
|
|||||||
document.head.appendChild(style);
|
document.head.appendChild(style);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 纯外观 preset:如果 kind=iframe,则用 iframe srcdoc 完全接管内部内容
|
// kind=iframe:用 iframe srcdoc 完全接管内部内容
|
||||||
if (preset.kind === 'iframe' && preset.html) {
|
if (preset.kind === 'iframe' && preset.html) {
|
||||||
// 清空旧文字容器
|
|
||||||
titleEl.textContent = '';
|
titleEl.textContent = '';
|
||||||
subtitleEl.textContent = '';
|
subtitleEl.textContent = '';
|
||||||
if (!iframeEl) {
|
if (!iframeEl) {
|
||||||
@@ -204,41 +265,482 @@
|
|||||||
ltInner.innerHTML = '';
|
ltInner.innerHTML = '';
|
||||||
ltInner.appendChild(iframeEl);
|
ltInner.appendChild(iframeEl);
|
||||||
}
|
}
|
||||||
// Fill placeholders with content data before setting srcdoc
|
iframeEl.srcdoc = fillPlaceholders(preset.html, contentData || {});
|
||||||
const processedHtml = fillPlaceholders(preset.html, contentData || {});
|
|
||||||
iframeEl.srcdoc = processedHtml;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
resetAnimation();
|
resetAnimation();
|
||||||
lt.classList.add('show');
|
lt.classList.add('show');
|
||||||
|
|
||||||
// Schedule auto-hide if duration > 0
|
|
||||||
if (typeof autoHideDuration === 'number' && autoHideDuration > 0) {
|
if (typeof autoHideDuration === 'number' && autoHideDuration > 0) {
|
||||||
scheduleAutoHide(autoHideDuration);
|
scheduleAutoHide(autoHideDuration);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── LRC 字幕 ──────────────────────────────────────────────
|
||||||
|
const lrcLayer = document.getElementById('lrcLayer');
|
||||||
|
const lrcBox = document.getElementById('lrcBox');
|
||||||
|
const lrcText = document.getElementById('lrcText');
|
||||||
|
const lrcNext = document.getElementById('lrcNext');
|
||||||
|
|
||||||
|
/** 服务器时间 - 本地时间(毫秒) */
|
||||||
|
let clockSkewMs = 0;
|
||||||
|
let clockSamples = [];
|
||||||
|
let wsRef = null;
|
||||||
|
|
||||||
|
const lrc = {
|
||||||
|
active: false,
|
||||||
|
cues: [],
|
||||||
|
style: null,
|
||||||
|
anchor: 0,
|
||||||
|
paused: false,
|
||||||
|
pausedElapsed: 0,
|
||||||
|
tailMs: 4000,
|
||||||
|
shownIndex: -2,
|
||||||
|
tickTimer: null,
|
||||||
|
spans: null,
|
||||||
|
cue: null,
|
||||||
|
phase: null,
|
||||||
|
phaseTimer: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const LRC_OUTROS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
|
||||||
|
|
||||||
|
let lrcCustomStyleEl = null;
|
||||||
|
|
||||||
|
function applyLrcCustomCss(css) {
|
||||||
|
if (!lrcCustomStyleEl) {
|
||||||
|
lrcCustomStyleEl = document.createElement('style');
|
||||||
|
lrcCustomStyleEl.id = 'lrc-custom-style';
|
||||||
|
document.head.appendChild(lrcCustomStyleEl);
|
||||||
|
}
|
||||||
|
lrcCustomStyleEl.textContent = css || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateClockSkew(t0, serverNow) {
|
||||||
|
const now = Date.now();
|
||||||
|
const rtt = Math.max(0, now - t0);
|
||||||
|
const sample = serverNow - (t0 + rtt / 2);
|
||||||
|
clockSamples.push(sample);
|
||||||
|
if (clockSamples.length > 7) clockSamples.shift();
|
||||||
|
const sorted = clockSamples.slice().sort((a, b) => a - b);
|
||||||
|
clockSkewMs = sorted[Math.floor(sorted.length / 2)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestClockSync() {
|
||||||
|
if (wsRef && wsRef.readyState === WebSocket.OPEN) {
|
||||||
|
wsRef.send(JSON.stringify({ type: 'clock', t0: Date.now() }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function serverNow() {
|
||||||
|
return Date.now() + clockSkewMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLrcTiming(style) {
|
||||||
|
const s = style || {};
|
||||||
|
const clamp = (value, min, max, fallback) => {
|
||||||
|
const n = Number(value);
|
||||||
|
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
inMs: clamp(s.enterDurationMs, 0, 10000, 300),
|
||||||
|
holdMs: clamp(s.holdDurationMs, 0, 10000, 0),
|
||||||
|
outMs: clamp(s.outDurationMs, 0, 10000, 260),
|
||||||
|
shrinkMs: clamp(s.shrinkDurationMs, 0, 20000, 0),
|
||||||
|
shrinkTo: clamp(s.holdShrinkTo, 0.3, 1, 1),
|
||||||
|
blurPx: clamp(s.blurPx, 0, 60, 10),
|
||||||
|
outro: LRC_OUTROS.includes(s.outro) ? s.outro : 'fade',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每句字幕的可用时长 = 到下一句的距离(最后一句用 tailMs)。
|
||||||
|
* 入场和回缩都必须在下一句出现前完成,否则观众看到的永远是「没缩完就跳走」。
|
||||||
|
*/
|
||||||
|
function cueWindowMs(index) {
|
||||||
|
const cue = lrc.cues[index];
|
||||||
|
if (!cue) return 0;
|
||||||
|
const next = lrc.cues[index + 1];
|
||||||
|
const end = next ? next.t : cue.t + (Number(lrc.tailMs) || 0);
|
||||||
|
return Math.max(0, end - cue.t);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fitTimingToWindow(timing, windowMs) {
|
||||||
|
// 至少给回缩留 40% 的时间,否则回缩没有观感
|
||||||
|
const available = Math.max(120, windowMs || 0);
|
||||||
|
let inMs = timing.inMs;
|
||||||
|
let shrinkMs = timing.shrinkMs;
|
||||||
|
const total = inMs + shrinkMs;
|
||||||
|
if (total <= available) return { inMs, shrinkMs, fitted: false };
|
||||||
|
const inFloor = Math.min(inMs, available * 0.45);
|
||||||
|
inMs = Math.round(inFloor);
|
||||||
|
shrinkMs = Math.round(Math.max(120, Math.min(shrinkMs, available - inMs)));
|
||||||
|
return { inMs, shrinkMs, fitted: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLrcStyle(style) {
|
||||||
|
const s = style || {};
|
||||||
|
lrcLayer.className = 'lrc-layer';
|
||||||
|
lrcLayer.classList.add('pos-' + (s.position || 'bottom'));
|
||||||
|
lrcLayer.classList.add('lrc-align-' + (s.align || 'center'));
|
||||||
|
lrcLayer.classList.add('lrc-anim-' + (s.animation || 'fade'));
|
||||||
|
const timing = getLrcTiming(s);
|
||||||
|
lrcLayer.classList.add('lrc-out-' + timing.outro);
|
||||||
|
lrcLayer.style.setProperty('--lrc-in-dur', timing.inMs + 'ms');
|
||||||
|
lrcLayer.style.setProperty('--lrc-out-dur', timing.outMs + 'ms');
|
||||||
|
lrcLayer.style.setProperty('--lrc-shrink-dur', timing.shrinkMs + 'ms');
|
||||||
|
lrcLayer.style.setProperty('--lrc-shrink-to', String(timing.shrinkTo)); lrcLayer.style.setProperty('--lrc-blur-px', timing.blurPx + 'px');
|
||||||
|
lrcLayer.style.paddingBottom = '0px';
|
||||||
|
lrcLayer.style.paddingTop = '0px';
|
||||||
|
|
||||||
|
if (s.position === 'bottom') {
|
||||||
|
lrcLayer.style.paddingBottom = (Number(s.bottomOffsetVh) || 0) + 'vh';
|
||||||
|
} else if (s.position === 'top') {
|
||||||
|
lrcLayer.style.paddingTop = (Number(s.bottomOffsetVh) || 0) + 'vh';
|
||||||
|
}
|
||||||
|
|
||||||
|
lrcBox.style.maxWidth = (Number(s.maxWidthPercent) || 86) + '%';
|
||||||
|
lrcBox.style.background = s.backgroundEnabled === false
|
||||||
|
? 'transparent'
|
||||||
|
: (s.background || 'transparent');
|
||||||
|
lrcBox.style.padding = (Number(s.paddingY) || 0) + 'px ' + (Number(s.paddingX) || 0) + 'px';
|
||||||
|
lrcBox.style.borderRadius = (Number(s.borderRadius) || 0) + 'px';
|
||||||
|
|
||||||
|
const shadow = s.textShadowEnabled === false ? 'none' : (s.textShadow || 'none');
|
||||||
|
lrcText.style.fontFamily = s.fontFamily || '';
|
||||||
|
lrcText.style.fontSize = (Number(s.fontSize) || 42) + 'px';
|
||||||
|
lrcText.style.fontWeight = String(Number(s.fontWeight) || 700);
|
||||||
|
lrcText.style.color = s.color || '#fff';
|
||||||
|
lrcText.style.letterSpacing = (Number(s.letterSpacing) || 0) + 'px';
|
||||||
|
lrcText.style.lineHeight = String(Number(s.lineHeight) || 1.35);
|
||||||
|
lrcText.style.textShadow = shadow;
|
||||||
|
lrcText.style.setProperty('--lrc-color', s.color || '#fff');
|
||||||
|
lrcText.style.setProperty(
|
||||||
|
'--lrc-karaoke-pending',
|
||||||
|
s.karaokePendingColor || 'rgba(255, 255, 255, 0.45)'
|
||||||
|
);
|
||||||
|
|
||||||
|
lrcNext.style.fontFamily = s.fontFamily || '';
|
||||||
|
lrcNext.style.fontSize = ((Number(s.fontSize) || 42) * (Number(s.nextLineScale) || 0.68)) + 'px';
|
||||||
|
lrcNext.style.color = s.nextLineColor || 'rgba(255,255,255,0.55)';
|
||||||
|
lrcNext.style.textShadow = shadow;
|
||||||
|
lrcNext.style.display = s.showNextLine === false ? 'none' : '';
|
||||||
|
|
||||||
|
// 下一句和当前句同属 .lrc-text 的兄弟节点,回缩时一起缩放更自然
|
||||||
|
lrcNext.style.transformOrigin = 'center';
|
||||||
|
|
||||||
|
applyLrcCustomCss(s.customCss || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function findCueIndex(elapsed) {
|
||||||
|
const cues = lrc.cues;
|
||||||
|
if (!cues.length) return -1;
|
||||||
|
if (elapsed < cues[0].t) return -1;
|
||||||
|
let lo = 0;
|
||||||
|
let hi = cues.length - 1;
|
||||||
|
let result = 0;
|
||||||
|
while (lo <= hi) {
|
||||||
|
const mid = (lo + hi) >> 1;
|
||||||
|
if (cues[mid].t <= elapsed) {
|
||||||
|
result = mid;
|
||||||
|
lo = mid + 1;
|
||||||
|
} else {
|
||||||
|
hi = mid - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideLrc() {
|
||||||
|
lrcLayer.classList.remove('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
function showLrc() {
|
||||||
|
lrcLayer.classList.add('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 入场 / 停留回缩 / 出场 状态机 ──────────────────────────
|
||||||
|
function setPhase(phase) {
|
||||||
|
if (lrc.phase === phase) return;
|
||||||
|
lrc.phase = phase;
|
||||||
|
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
|
||||||
|
if (phase) lrcLayer.classList.add('lrc-state-' + phase);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearPhaseTimer() {
|
||||||
|
if (lrc.phaseTimer) {
|
||||||
|
clearTimeout(lrc.phaseTimer);
|
||||||
|
lrc.phaseTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function restartEntrance(cue, index) {
|
||||||
|
clearPhaseTimer();
|
||||||
|
// 关键:先把上一句残留的 hold 状态去掉并让浏览器结算掉旧的回缩过渡,
|
||||||
|
// 否则新一句会从上一次的缩小值继续,看起来像「回缩瞬间完成」或「根本不动」。
|
||||||
|
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
|
||||||
|
lrc.phase = null;
|
||||||
|
lrcText.style.transition = 'none';
|
||||||
|
lrcText.style.transform = 'scale(1)';
|
||||||
|
void lrcText.offsetWidth; // 强制重排,让上面的重置立即生效
|
||||||
|
lrcText.style.transition = '';
|
||||||
|
lrcText.style.transform = '';
|
||||||
|
|
||||||
|
// 入场 + 回缩必须塞进「到下一句的时间」里,否则回缩永远播不完
|
||||||
|
const timing = getLrcTiming(lrc.style);
|
||||||
|
const fitted = fitTimingToWindow(timing, cueWindowMs(index));
|
||||||
|
lrcLayer.style.setProperty('--lrc-in-dur', fitted.inMs + 'ms');
|
||||||
|
lrcLayer.style.setProperty('--lrc-shrink-dur', fitted.shrinkMs + 'ms');
|
||||||
|
|
||||||
|
setPhase('entering');
|
||||||
|
showLrc();
|
||||||
|
|
||||||
|
const current = cue;
|
||||||
|
lrc.phaseTimer = setTimeout(() => {
|
||||||
|
lrc.phaseTimer = null;
|
||||||
|
if (!lrc.active || lrc.cue !== current) return;
|
||||||
|
// 入场结束 -> 停留阶段(从 1 开始缓慢回缩)
|
||||||
|
setPhase('hold');
|
||||||
|
}, fitted.inMs + timing.holdMs + 20);
|
||||||
|
|
||||||
|
return fitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
function beginOutro(onDone) {
|
||||||
|
clearPhaseTimer();
|
||||||
|
const timing = getLrcTiming(lrc.style);
|
||||||
|
lrc.cue = null;
|
||||||
|
if (timing.outro === 'none' || timing.outMs <= 0) {
|
||||||
|
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
|
||||||
|
lrc.phase = null;
|
||||||
|
hideLrc();
|
||||||
|
onDone();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 出场动画要作用在「当前可见的尺寸」上,先把回缩的 transform 固定住再切到 leaving
|
||||||
|
const computed = getComputedStyle(lrcText).transform;
|
||||||
|
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
|
||||||
|
lrc.phase = null;
|
||||||
|
lrcText.style.transition = 'none';
|
||||||
|
if (computed && computed !== 'none') lrcText.style.transform = computed;
|
||||||
|
void lrcText.offsetWidth;
|
||||||
|
lrcText.style.transition = '';
|
||||||
|
lrcText.style.transform = '';
|
||||||
|
|
||||||
|
setPhase('leaving');
|
||||||
|
lrc.phaseTimer = setTimeout(() => {
|
||||||
|
lrc.phaseTimer = null;
|
||||||
|
setPhase(null);
|
||||||
|
hideLrc();
|
||||||
|
if (onDone) onDone();
|
||||||
|
}, timing.outMs + 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearLrcContent() {
|
||||||
|
lrc.cue = null;
|
||||||
|
lrc.spans = null;
|
||||||
|
lrcText.textContent = '';
|
||||||
|
lrcNext.textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function cueUsesKaraoke(cue) {
|
||||||
|
return !!(lrc.style && lrc.style.karaoke !== false && cue
|
||||||
|
&& Array.isArray(cue.segments) && cue.segments.length >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildKaraoke(cue) {
|
||||||
|
lrcText.textContent = '';
|
||||||
|
const spans = [];
|
||||||
|
cue.segments.forEach((segment) => {
|
||||||
|
const span = document.createElement('span');
|
||||||
|
span.className = 'lrc-word is-pending';
|
||||||
|
span.dataset.at = String(segment.at);
|
||||||
|
span.textContent = segment.text;
|
||||||
|
lrcText.appendChild(span);
|
||||||
|
spans.push(span);
|
||||||
|
});
|
||||||
|
lrc.spans = spans;
|
||||||
|
updateKaraoke(currentElapsed());
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateKaraoke(elapsed) {
|
||||||
|
if (!lrc.spans || !lrc.spans.length) return;
|
||||||
|
let current = -1;
|
||||||
|
for (let i = 0; i < lrc.spans.length; i += 1) {
|
||||||
|
if (Number(lrc.spans[i].dataset.at) <= elapsed) current = i;
|
||||||
|
}
|
||||||
|
for (let i = 0; i < lrc.spans.length; i += 1) {
|
||||||
|
const sung = i <= current;
|
||||||
|
lrc.spans[i].classList.toggle('is-sung', sung);
|
||||||
|
lrc.spans[i].classList.toggle('is-pending', !sung);
|
||||||
|
lrc.spans[i].classList.toggle('is-current', i === current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCue(index) {
|
||||||
|
if (index === lrc.shownIndex) return;
|
||||||
|
|
||||||
|
if (index < 0) {
|
||||||
|
// 还没到第一句:只有本次播放尚未入场过时才清空,避免打断正在进行的出场动画
|
||||||
|
const neverShown = lrc.shownIndex === -2;
|
||||||
|
lrc.shownIndex = -2;
|
||||||
|
if (neverShown) {
|
||||||
|
if (lrc.spans) {
|
||||||
|
lrc.spans = null;
|
||||||
|
lrcText.textContent = '';
|
||||||
|
lrcNext.textContent = '';
|
||||||
|
}
|
||||||
|
} else if (lrc.cue) {
|
||||||
|
lrc.cue = null;
|
||||||
|
lrc.spans = null;
|
||||||
|
lrcText.textContent = '';
|
||||||
|
lrcNext.textContent = '';
|
||||||
|
}
|
||||||
|
hideLrc();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lrc.shownIndex = index;
|
||||||
|
const cue = lrc.cues[index];
|
||||||
|
if (!cue) {
|
||||||
|
hideLrc();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cueUsesKaraoke(cue)) {
|
||||||
|
buildKaraoke(cue);
|
||||||
|
} else {
|
||||||
|
lrc.spans = null;
|
||||||
|
lrcText.textContent = cue.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = lrc.cues[index + 1];
|
||||||
|
// 逐字模式下下一句也可能带增强标签,这里统一只显示纯文本
|
||||||
|
lrcNext.textContent = next ? next.text : '';
|
||||||
|
|
||||||
|
lrc.cue = cue;
|
||||||
|
lrc.cueIndex = index;
|
||||||
|
restartEntrance(cue, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentElapsed() {
|
||||||
|
if (lrc.paused) return lrc.pausedElapsed;
|
||||||
|
return serverNow() - lrc.anchor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tickLrc() {
|
||||||
|
if (!lrc.active) return;
|
||||||
|
const elapsed = currentElapsed();
|
||||||
|
const last = lrc.cues[lrc.cues.length - 1];
|
||||||
|
if (last && elapsed > last.t + lrc.tailMs) {
|
||||||
|
// 整段结束:播放淡出/出场动画
|
||||||
|
if (lrc.cue) beginOutro();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
renderCue(findCueIndex(elapsed));
|
||||||
|
updateKaraoke(elapsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startTicker() {
|
||||||
|
if (lrc.tickTimer) return;
|
||||||
|
lrc.tickTimer = setInterval(tickLrc, 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopTicker() {
|
||||||
|
if (lrc.tickTimer) {
|
||||||
|
clearInterval(lrc.tickTimer);
|
||||||
|
lrc.tickTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLrcState(state) {
|
||||||
|
if (!state || !state.playing) {
|
||||||
|
const reason = state && state.reason;
|
||||||
|
const wasActive = lrc.active;
|
||||||
|
lrc.active = false;
|
||||||
|
stopTicker();
|
||||||
|
if (!wasActive) {
|
||||||
|
// 其他客户端已经播完并淡出,这里直接收尾
|
||||||
|
clearPhaseTimer();
|
||||||
|
setPhase(null);
|
||||||
|
hideLrc();
|
||||||
|
clearLrcContent();
|
||||||
|
lrc.shownIndex = -2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (lrc.cue) {
|
||||||
|
// 播放被停止/清空:走一遍出场动画再清空
|
||||||
|
beginOutro(clearLrcContent);
|
||||||
|
} else {
|
||||||
|
clearLrcContent();
|
||||||
|
}
|
||||||
|
lrc.shownIndex = -2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isSameRun = lrc.active && lrc.anchor === state.anchor && lrc.presetId === state.presetId;
|
||||||
|
lrc.active = true;
|
||||||
|
lrc.presetId = state.presetId;
|
||||||
|
lrc.cues = Array.isArray(state.cues) ? state.cues : [];
|
||||||
|
lrc.style = state.style || {};
|
||||||
|
lrc.anchor = state.anchor;
|
||||||
|
lrc.paused = !!state.paused;
|
||||||
|
lrc.pausedElapsed = Number(state.pausedElapsed) || 0;
|
||||||
|
lrc.tailMs = Number(state.tailMs) || 0;
|
||||||
|
|
||||||
|
if (!isSameRun) {
|
||||||
|
applyLrcStyle(lrc.style);
|
||||||
|
lrc.shownIndex = -2;
|
||||||
|
}
|
||||||
|
|
||||||
|
startTicker();
|
||||||
|
tickLrc();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── WebSocket ────────────────────────────────────────────
|
||||||
|
let clockTimer = null;
|
||||||
|
|
||||||
function connectWs() {
|
function connectWs() {
|
||||||
const loc = window.location;
|
const loc = window.location;
|
||||||
const proto = loc.protocol === 'https:' ? 'wss:' : 'ws:';
|
const proto = loc.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
const wsUrl = proto + '//' + loc.host;
|
const ws = new WebSocket(proto + '//' + loc.host);
|
||||||
const ws = new WebSocket(wsUrl);
|
wsRef = ws;
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
requestClockSync();
|
||||||
|
if (clockTimer) clearInterval(clockTimer);
|
||||||
|
clockTimer = setInterval(requestClockSync, 20000);
|
||||||
|
};
|
||||||
|
|
||||||
ws.onmessage = (event) => {
|
ws.onmessage = (event) => {
|
||||||
|
let msg;
|
||||||
try {
|
try {
|
||||||
const msg = JSON.parse(event.data);
|
msg = JSON.parse(event.data);
|
||||||
if (msg.type === 'activePreset') {
|
|
||||||
applyPreset(msg.preset, msg.contentData, msg.autoHideDuration);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('WS message parse error', e);
|
console.error('WS message parse error', e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.type === 'activePreset') {
|
||||||
|
applyPreset(msg.preset, msg.contentData, msg.autoHideDuration);
|
||||||
|
} else if (msg.type === 'lrcState') {
|
||||||
|
applyLrcState(msg.state);
|
||||||
|
} else if (msg.type === 'clock') {
|
||||||
|
estimateClockSkew(Number(msg.t0) || 0, Number(msg.serverNow) || Date.now());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ws.onclose = () => {
|
ws.onclose = () => {
|
||||||
// simple retry
|
wsRef = null;
|
||||||
|
if (clockTimer) clearInterval(clockTimer);
|
||||||
|
clockTimer = null;
|
||||||
|
stopTicker();
|
||||||
|
// 断线时保留最后一帧字幕,重连后会收到完整状态并重新同步
|
||||||
setTimeout(connectWs, 2000);
|
setTimeout(connectWs, 2000);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
ws.onerror = () => {
|
||||||
|
try { ws.close(); } catch (_) { /* ignore */ }
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
connectWs();
|
connectWs();
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<style>
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
||||||
|
color: #fff;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.wrap {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 10px 16px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.tag {
|
||||||
|
font-size: 11px;
|
||||||
|
letter-spacing: 0.18em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
.title {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
.subtitle {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<div class="tag">{{tag}}</div>
|
||||||
|
<div class="title">{{mainTitle}}</div>
|
||||||
|
<div class="subtitle">{{subtitle}}</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
[ti:示例曲目]
|
||||||
|
[ar:示例歌手]
|
||||||
|
[al:示例专辑]
|
||||||
|
[by:obs-lowerthird]
|
||||||
|
[offset:0]
|
||||||
|
[00:00.00]作词:示例词作者
|
||||||
|
[00:00.40]作曲:示例曲作者
|
||||||
|
[00:00.80]编曲:示例编曲人
|
||||||
|
[00:01.20]制作人:示例制作人
|
||||||
|
[00:02.00]<00:02.00>第一句<00:02.65>歌词<00:03.20>从打点位置开始
|
||||||
|
[00:05.20]<00:05.20>第二句<00:05.80>跟着<00:06.40>时间轴出现
|
||||||
|
[00:08.60]<00:08.60>第三句<00:09.20>继续<00:09.80>往下走
|
||||||
|
[00:11.80]<00:11.80>第四句<00:12.40>用来<00:13.00>检查自动偏移
|
||||||
|
[00:15.00]
|
||||||
|
[00:17.40]<00:17.40>副歌<00:18.10>第一句
|
||||||
|
[00:20.60]副歌第二句
|
||||||
|
[00:24.00]最后一句结束后会自动隐藏
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"appearancePresets": [
|
||||||
|
{
|
||||||
|
"id": "appearance-default-1",
|
||||||
|
"name": "默认 · 右侧信息区",
|
||||||
|
"kind": "iframe",
|
||||||
|
"align": "right",
|
||||||
|
"themeColor": "",
|
||||||
|
"extraCss": "",
|
||||||
|
"fieldDefs": [
|
||||||
|
{ "key": "tag", "label": "标签", "defaultValue": "LIVE 直播" },
|
||||||
|
{ "key": "mainTitle", "label": "主标题", "defaultValue": "示例主标题" },
|
||||||
|
{ "key": "subtitle", "label": "副标题", "defaultValue": "示例副标题" }
|
||||||
|
],
|
||||||
|
"htmlFile": "default-appearance.html"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"contentPresets": [
|
||||||
|
{
|
||||||
|
"id": "content-default-1",
|
||||||
|
"name": "示例内容 · 开场",
|
||||||
|
"appearancePresetId": "appearance-default-1",
|
||||||
|
"fields": {
|
||||||
|
"tag": "LIVE 直播",
|
||||||
|
"mainTitle": "欢迎来到直播间",
|
||||||
|
"subtitle": "这是一个内容预设示例"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "content-default-2",
|
||||||
|
"name": "示例内容 · 嘉宾介绍",
|
||||||
|
"appearancePresetId": "appearance-default-1",
|
||||||
|
"fields": {
|
||||||
|
"tag": "GUEST 嘉宾",
|
||||||
|
"mainTitle": "嘉宾姓名",
|
||||||
|
"subtitle": "职位 / 简介"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"lrcPresets": [
|
||||||
|
{
|
||||||
|
"id": "lrc-default-1",
|
||||||
|
"name": "示例 · LRC 字幕",
|
||||||
|
"sourceFile": "default.lrc",
|
||||||
|
"filters": {
|
||||||
|
"dropCreditLines": true,
|
||||||
|
"dropUntimed": true
|
||||||
|
},
|
||||||
|
"range": { "startIndex": 0, "endIndex": null },
|
||||||
|
"offsetMs": 0,
|
||||||
|
"tailMs": 4000,
|
||||||
|
"style": {
|
||||||
|
"position": "bottom",
|
||||||
|
"fontSize": 42,
|
||||||
|
"background": "rgba(0, 0, 0, 0.55)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {
|
||||||
|
"autoHideDuration": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,333 +1,619 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const http = require('http');
|
const http = require('http');
|
||||||
const WebSocket = require('ws');
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const { createStores } = require('./lib/store');
|
||||||
|
const { loadSeed } = require('./lib/seed');
|
||||||
|
const lrcLib = require('./lib/lrc');
|
||||||
|
const models = require('./lib/models');
|
||||||
|
|
||||||
|
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
|
||||||
|
const PORT = Number(process.env.PORT) || 30001;
|
||||||
|
|
||||||
|
const seed = loadSeed();
|
||||||
|
const stores = createStores(DATA_DIR, {
|
||||||
|
appearancePresets: seed.appearancePresets,
|
||||||
|
contentPresets: seed.contentPresets,
|
||||||
|
lrcPresets: seed.lrcPresets,
|
||||||
|
settings: seed.settings,
|
||||||
|
normalizeAppearancePreset: models.normalizeAppearancePreset,
|
||||||
|
normalizeContentPreset: models.normalizeContentPreset,
|
||||||
|
normalizeLrcPreset: lrcLib.normalizeLrcPreset,
|
||||||
|
});
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
const wss = new WebSocket.Server({ server });
|
const wss = new WebSocket.Server({ server });
|
||||||
|
|
||||||
// Global settings
|
app.disable('x-powered-by');
|
||||||
let settings = {
|
app.use(express.json({ limit: '8mb' }));
|
||||||
autoHideDuration: 0 // 0 = disabled, >0 = ms to auto-hide
|
|
||||||
};
|
|
||||||
|
|
||||||
// Appearance presets: define the visual template with {{placeholder}} support
|
|
||||||
let presets = [
|
|
||||||
{
|
|
||||||
id: 'preset-gala-iframe-1',
|
|
||||||
name: '测试',
|
|
||||||
kind: 'iframe',
|
|
||||||
align: 'right',
|
|
||||||
themeColor: '',
|
|
||||||
extraCss: '',
|
|
||||||
fieldDefs: [
|
|
||||||
{ key: 'tag', label: '标签', defaultValue: 'TEST 测试' },
|
|
||||||
{ key: 'mainTitle', label: '主标题', defaultValue: '测试内容' },
|
|
||||||
{ key: 'subtitle', label: '副标题', defaultValue: '' }
|
|
||||||
],
|
|
||||||
html: `<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<style>
|
|
||||||
html, body {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
overflow: hidden;
|
|
||||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
||||||
color: #fff;
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
.wrap {
|
|
||||||
position: relative;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: flex-start;
|
|
||||||
padding: 10px 16px;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
.tag {
|
|
||||||
font-size: 11px;
|
|
||||||
letter-spacing: 0.18em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
opacity: 0.85;
|
|
||||||
}
|
|
||||||
.title {
|
|
||||||
margin-top: 6px;
|
|
||||||
font-size: 20px;
|
|
||||||
font-weight: 800;
|
|
||||||
}
|
|
||||||
.subtitle {
|
|
||||||
margin-top: 4px;
|
|
||||||
font-size: 14px;
|
|
||||||
opacity: 0.9;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="wrap">
|
|
||||||
<div class="tag">{{tag}}</div>
|
|
||||||
<div class="title">{{mainTitle}}</div>
|
|
||||||
<div class="subtitle">{{subtitle}}</div>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>`
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
// Content presets: define field values to fill into appearance preset templates
|
|
||||||
let contentPresets = [
|
|
||||||
{
|
|
||||||
id: 'content-preset-1',
|
|
||||||
name: '测试内容 1',
|
|
||||||
appearancePresetId: 'preset-gala-iframe-1',
|
|
||||||
fields: {
|
|
||||||
tag: 'TEST TAG',
|
|
||||||
mainTitle: '测试主标题 1',
|
|
||||||
subtitle: '测试副标题 1'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'content-preset-2',
|
|
||||||
name: '测试内容 2',
|
|
||||||
appearancePresetId: 'preset-gala-iframe-1',
|
|
||||||
fields: {
|
|
||||||
tag: 'TEST TAG 2',
|
|
||||||
mainTitle: '测试主标题 2',
|
|
||||||
subtitle: '测试副标题 2'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
|
// ── 运行状态(不持久化:重启后默认全部隐藏) ──────────────────────────────────
|
||||||
let activePresetId = null;
|
let activePresetId = null;
|
||||||
let activeContentPresetId = null;
|
let activeContentPresetId = null;
|
||||||
let activeFieldOverrides = {};
|
let activeFieldOverrides = {};
|
||||||
|
|
||||||
app.use(express.json());
|
/** @type {null | {
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
* presetId: string, presetName: string, cues: any[], style: any,
|
||||||
|
* anchor: number, paused: boolean, pausedElapsed: number,
|
||||||
|
* totalMs: number, endMs: number, tailMs: number, offsetMs: number,
|
||||||
|
* startedAt: number, leadInMs: number
|
||||||
|
* }} */
|
||||||
|
let lrcPlayback = null;
|
||||||
|
let lrcEndTimer = null;
|
||||||
|
|
||||||
// ── Settings API ─────────────────────────────────────────────────────────────
|
const MAX_TIMER_DELAY = 2_147_483_647;
|
||||||
|
|
||||||
|
// ── 静态资源 ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
app.use(express.static(path.join(__dirname, 'public'), {
|
||||||
|
etag: true,
|
||||||
|
maxAge: 0,
|
||||||
|
setHeaders(res, filePath) {
|
||||||
|
if (filePath.endsWith('.html')) res.setHeader('Cache-Control', 'no-cache');
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ── 工具函数 ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function fail(res, status, message) {
|
||||||
|
return res.status(status).json({ error: message });
|
||||||
|
}
|
||||||
|
|
||||||
|
function settingsValue() {
|
||||||
|
return stores.settings.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeFieldOverrides(input) {
|
||||||
|
if (!input || typeof input !== 'object' || Array.isArray(input)) return {};
|
||||||
|
const result = {};
|
||||||
|
for (const [key, value] of Object.entries(input)) {
|
||||||
|
if (!/^[\w-]+$/.test(key)) continue;
|
||||||
|
result[key] = String(value == null ? '' : value).slice(0, 20_000);
|
||||||
|
if (Object.keys(result).length >= 80) break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只保留请求里显式提供的字段,避免 PUT 局部更新把未传字段清空 */
|
||||||
|
function pickDefined(source, keys) {
|
||||||
|
const result = {};
|
||||||
|
if (!source || typeof source !== 'object') return result;
|
||||||
|
for (const key of keys) {
|
||||||
|
if (source[key] !== undefined) result[key] = source[key];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getActiveAppearancePreset() {
|
||||||
|
if (!activePresetId) return null;
|
||||||
|
return stores.appearancePresets.find(activePresetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getContentData() {
|
||||||
|
const fields = {};
|
||||||
|
const appearance = getActiveAppearancePreset();
|
||||||
|
if (appearance && appearance.fieldDefs) {
|
||||||
|
for (const field of appearance.fieldDefs) {
|
||||||
|
fields[field.key] = field.defaultValue || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (activeContentPresetId) {
|
||||||
|
const content = stores.contentPresets.find(activeContentPresetId);
|
||||||
|
if (content) Object.assign(fields, content.fields);
|
||||||
|
}
|
||||||
|
Object.assign(fields, activeFieldOverrides);
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getActivePayload() {
|
||||||
|
return {
|
||||||
|
type: 'activePreset',
|
||||||
|
preset: getActiveAppearancePreset(),
|
||||||
|
contentData: getContentData(),
|
||||||
|
autoHideDuration: settingsValue().autoHideDuration,
|
||||||
|
activePresetId,
|
||||||
|
activeContentPresetId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function broadcastRaw(message) {
|
||||||
|
const text = JSON.stringify(message);
|
||||||
|
wss.clients.forEach((client) => {
|
||||||
|
if (client.readyState === WebSocket.OPEN) client.send(text);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function broadcastActive(autoHideDuration) {
|
||||||
|
const payload = getActivePayload();
|
||||||
|
if (typeof autoHideDuration === 'number') payload.autoHideDuration = autoHideDuration;
|
||||||
|
broadcastRaw(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── LRC 播放状态 ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function getLrcStatePayload() {
|
||||||
|
if (!lrcPlayback) return { type: 'lrcState', state: { playing: false } };
|
||||||
|
return {
|
||||||
|
type: 'lrcState',
|
||||||
|
state: {
|
||||||
|
playing: true,
|
||||||
|
paused: lrcPlayback.paused,
|
||||||
|
presetId: lrcPlayback.presetId,
|
||||||
|
presetName: lrcPlayback.presetName,
|
||||||
|
cues: lrcPlayback.cues,
|
||||||
|
style: lrcPlayback.style,
|
||||||
|
anchor: lrcPlayback.anchor,
|
||||||
|
pausedElapsed: lrcPlayback.pausedElapsed,
|
||||||
|
totalMs: lrcPlayback.totalMs,
|
||||||
|
endMs: lrcPlayback.endMs,
|
||||||
|
tailMs: lrcPlayback.tailMs,
|
||||||
|
offsetMs: lrcPlayback.offsetMs,
|
||||||
|
leadInMs: lrcPlayback.leadInMs,
|
||||||
|
startedAt: lrcPlayback.startedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function broadcastLrc() {
|
||||||
|
broadcastRaw(getLrcStatePayload());
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearLrcEndTimer() {
|
||||||
|
if (lrcEndTimer) {
|
||||||
|
clearTimeout(lrcEndTimer);
|
||||||
|
lrcEndTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleLrcEnd() {
|
||||||
|
clearLrcEndTimer();
|
||||||
|
if (!lrcPlayback || lrcPlayback.paused) return;
|
||||||
|
const delay = lrcPlayback.endMs - Date.now();
|
||||||
|
if (delay <= 0) {
|
||||||
|
stopLrc('ended');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lrcEndTimer = setTimeout(() => {
|
||||||
|
lrcEndTimer = null;
|
||||||
|
stopLrc('ended');
|
||||||
|
}, Math.min(delay, MAX_TIMER_DELAY));
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopLrc(reason) {
|
||||||
|
if (!lrcPlayback) return false;
|
||||||
|
clearLrcEndTimer();
|
||||||
|
lrcPlayback = null;
|
||||||
|
broadcastRaw({ type: 'lrcState', state: { playing: false, reason: reason || 'stopped' } });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTimelineForConfig(preset, overrides = {}) {
|
||||||
|
const source = typeof overrides.source === 'string' ? overrides.source : preset.source;
|
||||||
|
const filters = lrcLib.normalizeFilters({
|
||||||
|
...(preset.filters || {}),
|
||||||
|
...(overrides.filters && typeof overrides.filters === 'object' ? overrides.filters : {}),
|
||||||
|
});
|
||||||
|
const range = lrcLib.normalizeRange(overrides.range !== undefined ? overrides.range : preset.range);
|
||||||
|
const offsetMs = lrcLib.clampNumber(overrides.offsetMs, -60000, 60000, preset.offsetMs);
|
||||||
|
const tailMs = lrcLib.clampNumber(overrides.tailMs, 0, 60000, preset.tailMs);
|
||||||
|
const style = lrcLib.normalizeStyle({
|
||||||
|
...(preset.style || {}),
|
||||||
|
...(overrides.style && typeof overrides.style === 'object' ? overrides.style : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const parsed = lrcLib.parseLrc(source);
|
||||||
|
const timeline = lrcLib.buildTimeline(parsed, { filters, range, offsetMs, tailMs });
|
||||||
|
return { parsed, timeline, filters, range, offsetMs, tailMs, style, source };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 设置 API ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
app.get('/api/settings', (req, res) => {
|
app.get('/api/settings', (req, res) => {
|
||||||
res.json(settings);
|
res.json(settingsValue());
|
||||||
});
|
});
|
||||||
|
|
||||||
app.put('/api/settings', (req, res) => {
|
app.put('/api/settings', (req, res) => {
|
||||||
const { autoHideDuration } = req.body || {};
|
const next = { ...settingsValue() };
|
||||||
if (typeof autoHideDuration === 'number') {
|
if (req.body && req.body.autoHideDuration !== undefined) {
|
||||||
settings.autoHideDuration = Math.max(0, autoHideDuration);
|
const duration = Number(req.body.autoHideDuration);
|
||||||
|
if (!Number.isFinite(duration) || duration < 0) {
|
||||||
|
return fail(res, 400, 'autoHideDuration 必须是非负数字');
|
||||||
}
|
}
|
||||||
res.json(settings);
|
next.autoHideDuration = Math.min(Math.round(duration), 600_000);
|
||||||
|
}
|
||||||
|
stores.settings.update(next);
|
||||||
|
res.json(settingsValue());
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Appearance Presets API ────────────────────────────────────────────────────
|
// ── 外观预设 API ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
app.get('/api/presets', (req, res) => {
|
app.get('/api/presets', (req, res) => {
|
||||||
res.json({ presets, contentPresets, activePresetId, activeContentPresetId, settings });
|
res.json({
|
||||||
|
presets: stores.appearancePresets.list(),
|
||||||
|
contentPresets: stores.contentPresets.list(),
|
||||||
|
lrcPresets: stores.lrcPresets.list(),
|
||||||
|
lrcDefaults: {
|
||||||
|
filters: { ...lrcLib.DEFAULT_LRC_FILTERS },
|
||||||
|
style: { ...lrcLib.DEFAULT_LRC_STYLE },
|
||||||
|
timing: { ...lrcLib.DEFAULT_LRC_TIMING },
|
||||||
|
creditKeywords: lrcLib.DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
},
|
||||||
|
activePresetId,
|
||||||
|
activeContentPresetId,
|
||||||
|
settings: settingsValue(),
|
||||||
|
lrcState: getLrcStatePayload().state,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/lrc/defaults', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
filters: { ...lrcLib.DEFAULT_LRC_FILTERS },
|
||||||
|
style: { ...lrcLib.DEFAULT_LRC_STYLE },
|
||||||
|
timing: { ...lrcLib.DEFAULT_LRC_TIMING },
|
||||||
|
creditKeywords: lrcLib.DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/presets', (req, res) => {
|
app.post('/api/presets', (req, res) => {
|
||||||
const {
|
try {
|
||||||
name = '未命名外观',
|
const body = req.body || {};
|
||||||
kind = 'iframe',
|
const preset = stores.appearancePresets.insert({
|
||||||
html = '',
|
name: body.name,
|
||||||
themeColor = '',
|
kind: body.kind,
|
||||||
align = 'right',
|
html: body.html,
|
||||||
extraCss = '',
|
themeColor: body.themeColor,
|
||||||
fieldDefs = []
|
align: body.align,
|
||||||
} = req.body || {};
|
extraCss: body.extraCss,
|
||||||
const preset = {
|
fieldDefs: body.fieldDefs,
|
||||||
id: Date.now().toString(),
|
});
|
||||||
name,
|
|
||||||
kind,
|
|
||||||
html,
|
|
||||||
themeColor,
|
|
||||||
align,
|
|
||||||
extraCss,
|
|
||||||
fieldDefs
|
|
||||||
};
|
|
||||||
presets.push(preset);
|
|
||||||
res.json(preset);
|
res.json(preset);
|
||||||
|
} catch (err) {
|
||||||
|
fail(res, 400, err.message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.put('/api/presets/:id', (req, res) => {
|
app.put('/api/presets/:id', (req, res) => {
|
||||||
const { id } = req.params;
|
const body = req.body || {};
|
||||||
const idx = presets.findIndex(p => p.id === id);
|
try {
|
||||||
if (idx === -1) return res.status(404).json({ error: 'Not found' });
|
const updated = stores.appearancePresets.update(req.params.id,
|
||||||
const {
|
pickDefined(body, ['name', 'kind', 'html', 'themeColor', 'align', 'extraCss', 'fieldDefs']));
|
||||||
name = presets[idx].name,
|
if (!updated) return fail(res, 404, '预设不存在');
|
||||||
kind = presets[idx].kind,
|
if (activePresetId === updated.id) broadcastActive();
|
||||||
html = presets[idx].html,
|
res.json(updated);
|
||||||
themeColor = presets[idx].themeColor,
|
} catch (err) {
|
||||||
align = presets[idx].align,
|
fail(res, 400, err.message);
|
||||||
extraCss = presets[idx].extraCss,
|
}
|
||||||
fieldDefs = presets[idx].fieldDefs || []
|
|
||||||
} = req.body || {};
|
|
||||||
presets[idx] = { ...presets[idx], name, kind, html, themeColor, align, extraCss, fieldDefs };
|
|
||||||
res.json(presets[idx]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.delete('/api/presets/:id', (req, res) => {
|
app.delete('/api/presets/:id', (req, res) => {
|
||||||
const { id } = req.params;
|
const removed = stores.appearancePresets.remove(req.params.id);
|
||||||
presets = presets.filter(p => p.id !== id);
|
if (!removed) return fail(res, 404, '预设不存在');
|
||||||
if (activePresetId === id) {
|
if (activePresetId === req.params.id) {
|
||||||
activePresetId = null;
|
activePresetId = null;
|
||||||
broadcastActive();
|
activeContentPresetId = null;
|
||||||
|
activeFieldOverrides = {};
|
||||||
|
broadcastActive(0);
|
||||||
}
|
}
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Content Presets API ───────────────────────────────────────────────────────
|
// ── 内容预设 API ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
app.get('/api/content-presets', (req, res) => {
|
app.get('/api/content-presets', (req, res) => {
|
||||||
res.json(contentPresets);
|
res.json(stores.contentPresets.list());
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/content-presets', (req, res) => {
|
app.post('/api/content-presets', (req, res) => {
|
||||||
const {
|
try {
|
||||||
name = '未命名内容',
|
const body = req.body || {};
|
||||||
appearancePresetId = '',
|
const preset = stores.contentPresets.insert({
|
||||||
fields = {}
|
name: body.name,
|
||||||
} = req.body || {};
|
appearancePresetId: body.appearancePresetId,
|
||||||
const cp = {
|
fields: body.fields,
|
||||||
id: Date.now().toString(),
|
});
|
||||||
name,
|
res.json(preset);
|
||||||
appearancePresetId,
|
} catch (err) {
|
||||||
fields
|
fail(res, 400, err.message);
|
||||||
};
|
}
|
||||||
contentPresets.push(cp);
|
|
||||||
res.json(cp);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.put('/api/content-presets/:id', (req, res) => {
|
app.put('/api/content-presets/:id', (req, res) => {
|
||||||
const { id } = req.params;
|
const body = req.body || {};
|
||||||
const idx = contentPresets.findIndex(c => c.id === id);
|
try {
|
||||||
if (idx === -1) return res.status(404).json({ error: 'Not found' });
|
const updated = stores.contentPresets.update(req.params.id,
|
||||||
const {
|
pickDefined(body, ['name', 'appearancePresetId', 'fields']));
|
||||||
name = contentPresets[idx].name,
|
if (!updated) return fail(res, 404, '内容预设不存在');
|
||||||
appearancePresetId = contentPresets[idx].appearancePresetId,
|
if (activeContentPresetId === updated.id) broadcastActive();
|
||||||
fields = contentPresets[idx].fields
|
res.json(updated);
|
||||||
} = req.body || {};
|
} catch (err) {
|
||||||
contentPresets[idx] = { ...contentPresets[idx], name, appearancePresetId, fields };
|
fail(res, 400, err.message);
|
||||||
res.json(contentPresets[idx]);
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.delete('/api/content-presets/:id', (req, res) => {
|
app.delete('/api/content-presets/:id', (req, res) => {
|
||||||
const { id } = req.params;
|
const removed = stores.contentPresets.remove(req.params.id);
|
||||||
contentPresets = contentPresets.filter(c => c.id !== id);
|
if (!removed) return fail(res, 404, '内容预设不存在');
|
||||||
if (activeContentPresetId === id) {
|
if (activeContentPresetId === req.params.id) {
|
||||||
activeContentPresetId = null;
|
activeContentPresetId = null;
|
||||||
broadcastActive();
|
activeFieldOverrides = {};
|
||||||
|
broadcastActive(0);
|
||||||
}
|
}
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Activate ──────────────────────────────────────────────────────────────────
|
// ── 激活 API ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
// Activate by content preset id
|
|
||||||
app.post('/api/content-presets/:id/activate', (req, res) => {
|
app.post('/api/content-presets/:id/activate', (req, res) => {
|
||||||
const { id } = req.params;
|
const content = stores.contentPresets.find(req.params.id);
|
||||||
const cp = contentPresets.find(c => c.id === id);
|
if (!content) return fail(res, 404, '内容预设不存在');
|
||||||
if (!cp) return res.status(404).json({ error: 'Not found' });
|
|
||||||
|
|
||||||
activeContentPresetId = id;
|
activeContentPresetId = content.id;
|
||||||
activePresetId = cp.appearancePresetId;
|
activePresetId = content.appearancePresetId || null;
|
||||||
activeFieldOverrides = req.body?.fieldOverrides || {};
|
activeFieldOverrides = sanitizeFieldOverrides(req.body && req.body.fieldOverrides);
|
||||||
|
|
||||||
const bodyDuration = req.body && typeof req.body.autoHideDuration === 'number'
|
const overrideDuration = req.body && typeof req.body.autoHideDuration === 'number'
|
||||||
? req.body.autoHideDuration
|
? req.body.autoHideDuration
|
||||||
: null;
|
: null;
|
||||||
broadcastActive(bodyDuration !== null ? bodyDuration : settings.autoHideDuration);
|
broadcastActive(overrideDuration !== null ? overrideDuration : settingsValue().autoHideDuration);
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Activate by appearance preset id (legacy + direct)
|
|
||||||
app.post('/api/presets/:id/activate', (req, res) => {
|
app.post('/api/presets/:id/activate', (req, res) => {
|
||||||
const { id } = req.params;
|
const preset = stores.appearancePresets.find(req.params.id);
|
||||||
const preset = presets.find(p => p.id === id);
|
if (!preset) return fail(res, 404, '预设不存在');
|
||||||
if (!preset) return res.status(404).json({ error: 'Not found' });
|
|
||||||
|
|
||||||
activePresetId = id;
|
activePresetId = preset.id;
|
||||||
activeContentPresetId = null;
|
activeContentPresetId = null;
|
||||||
activeFieldOverrides = req.body?.fieldOverrides || {};
|
activeFieldOverrides = sanitizeFieldOverrides(req.body && req.body.fieldOverrides);
|
||||||
|
|
||||||
const bodyDuration = req.body && typeof req.body.autoHideDuration === 'number'
|
const overrideDuration = req.body && typeof req.body.autoHideDuration === 'number'
|
||||||
? req.body.autoHideDuration
|
? req.body.autoHideDuration
|
||||||
: null;
|
: null;
|
||||||
broadcastActive(bodyDuration !== null ? bodyDuration : settings.autoHideDuration);
|
broadcastActive(overrideDuration !== null ? overrideDuration : settingsValue().autoHideDuration);
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Clear active
|
|
||||||
app.post('/api/clear', (req, res) => {
|
app.post('/api/clear', (req, res) => {
|
||||||
activePresetId = null;
|
activePresetId = null;
|
||||||
activeContentPresetId = null;
|
activeContentPresetId = null;
|
||||||
activeFieldOverrides = {};
|
activeFieldOverrides = {};
|
||||||
broadcastActive(0);
|
broadcastActive(0);
|
||||||
|
stopLrc('cleared');
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
// ── LRC 预设 API ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function getActivePreset() {
|
app.get('/api/lrc-presets', (req, res) => {
|
||||||
if (!activePresetId) return null;
|
res.json(stores.lrcPresets.list());
|
||||||
return presets.find(p => p.id === activePresetId) || null;
|
});
|
||||||
|
|
||||||
|
app.get('/api/lrc-presets/:id', (req, res) => {
|
||||||
|
const preset = stores.lrcPresets.find(req.params.id);
|
||||||
|
if (!preset) return fail(res, 404, 'LRC 预设不存在');
|
||||||
|
res.json(preset);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/lrc-presets', (req, res) => {
|
||||||
|
try {
|
||||||
|
const body = req.body || {};
|
||||||
|
const preset = stores.lrcPresets.insert({
|
||||||
|
name: body.name,
|
||||||
|
source: body.source,
|
||||||
|
filters: body.filters,
|
||||||
|
range: body.range,
|
||||||
|
offsetMs: body.offsetMs,
|
||||||
|
tailMs: body.tailMs,
|
||||||
|
style: body.style,
|
||||||
|
});
|
||||||
|
res.json(preset);
|
||||||
|
} catch (err) {
|
||||||
|
fail(res, 400, err.message);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
function getContentData() {
|
app.put('/api/lrc-presets/:id', (req, res) => {
|
||||||
let fields = {};
|
const body = req.body || {};
|
||||||
// Start with appearance preset defaults
|
try {
|
||||||
const ap = getActivePreset();
|
const updated = stores.lrcPresets.update(req.params.id,
|
||||||
if (ap && ap.fieldDefs) {
|
pickDefined(body, ['name', 'source', 'filters', 'range', 'offsetMs', 'tailMs', 'style']));
|
||||||
for (const fd of ap.fieldDefs) {
|
if (!updated) return fail(res, 404, 'LRC 预设不存在');
|
||||||
fields[fd.key] = fd.defaultValue || '';
|
res.json(updated);
|
||||||
|
} catch (err) {
|
||||||
|
fail(res, 400, err.message);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/lrc-presets/:id', (req, res) => {
|
||||||
|
const removed = stores.lrcPresets.remove(req.params.id);
|
||||||
|
if (!removed) return fail(res, 404, 'LRC 预设不存在');
|
||||||
|
if (lrcPlayback && lrcPlayback.presetId === req.params.id) stopLrc('preset-deleted');
|
||||||
|
res.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 仅解析 / 预览,不保存 */
|
||||||
|
app.post('/api/lrc/parse', (req, res) => {
|
||||||
|
const body = req.body || {};
|
||||||
|
try {
|
||||||
|
const source = typeof body.source === 'string' ? body.source : '';
|
||||||
|
const filters = lrcLib.normalizeFilters(body.filters);
|
||||||
|
const requestedRange = lrcLib.normalizeRange(body.range);
|
||||||
|
const offsetMs = lrcLib.clampNumber(body.offsetMs, -60000, 60000, 0);
|
||||||
|
const tailMs = lrcLib.clampNumber(body.tailMs, 0, 60000, 4000);
|
||||||
|
|
||||||
|
const parsed = lrcLib.parseLrc(source);
|
||||||
|
const timeline = lrcLib.buildTimeline(parsed, {
|
||||||
|
filters,
|
||||||
|
range: requestedRange,
|
||||||
|
offsetMs,
|
||||||
|
tailMs,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
meta: parsed.meta,
|
||||||
|
metaOffsetMs: parsed.metaOffsetMs,
|
||||||
|
warnings: parsed.warnings,
|
||||||
|
filters,
|
||||||
|
requestedRange,
|
||||||
|
range: timeline.range,
|
||||||
|
stats: timeline.stats,
|
||||||
|
cues: timeline.cues,
|
||||||
|
candidates: timeline.candidates,
|
||||||
|
excluded: timeline.excluded.slice(0, 500),
|
||||||
|
totalMs: timeline.totalMs,
|
||||||
|
endMs: timeline.endMs,
|
||||||
|
offsetMs,
|
||||||
|
tailMs,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
fail(res, 400, err.message);
|
||||||
}
|
}
|
||||||
// Override with active content preset fields
|
});
|
||||||
if (activeContentPresetId) {
|
|
||||||
const cp = contentPresets.find(c => c.id === activeContentPresetId);
|
/** 开始播放:打点后第一句立即出现,后续按 LRC 时间轴走 */
|
||||||
if (cp) Object.assign(fields, cp.fields);
|
app.post('/api/lrc-presets/:id/play', (req, res) => {
|
||||||
|
const preset = stores.lrcPresets.find(req.params.id);
|
||||||
|
if (!preset) return fail(res, 404, 'LRC 预设不存在');
|
||||||
|
|
||||||
|
const body = req.body || {};
|
||||||
|
const leadInMs = lrcLib.clampNumber(body.leadInMs, 0, 60000, 0);
|
||||||
|
const overrides = body.overrides && typeof body.overrides === 'object' && !Array.isArray(body.overrides)
|
||||||
|
? body.overrides
|
||||||
|
: {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const built = buildTimelineForConfig(preset, overrides);
|
||||||
|
if (!built.timeline.cues.length) {
|
||||||
|
return fail(res, 400, '所选范围内没有可显示的字幕行,请检查 LRC 与范围设置');
|
||||||
}
|
}
|
||||||
// Override with per-activation overrides
|
|
||||||
Object.assign(fields, activeFieldOverrides);
|
const anchor = Date.now() + Math.round(leadInMs);
|
||||||
return fields;
|
const startedAt = Date.now();
|
||||||
|
lrcPlayback = {
|
||||||
|
presetId: preset.id,
|
||||||
|
presetName: preset.name,
|
||||||
|
cues: built.timeline.cues,
|
||||||
|
style: built.style,
|
||||||
|
anchor,
|
||||||
|
paused: false,
|
||||||
|
pausedElapsed: 0,
|
||||||
|
totalMs: built.timeline.totalMs,
|
||||||
|
endMs: anchor + built.timeline.endMs,
|
||||||
|
tailMs: built.timeline.tailMs,
|
||||||
|
offsetMs: built.timeline.offsetMs,
|
||||||
|
startedAt,
|
||||||
|
leadInMs: Math.round(leadInMs),
|
||||||
|
};
|
||||||
|
|
||||||
|
scheduleLrcEnd();
|
||||||
|
broadcastLrc();
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
state: getLrcStatePayload().state,
|
||||||
|
stats: built.timeline.stats,
|
||||||
|
totalMs: built.timeline.totalMs,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
fail(res, 400, err.message);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
function broadcastActive(autoHideDuration) {
|
app.post('/api/lrc/pause', (req, res) => {
|
||||||
const preset = getActivePreset();
|
if (!lrcPlayback) return fail(res, 409, '当前没有正在播放的 LRC 字幕');
|
||||||
const contentData = getContentData();
|
if (lrcPlayback.paused) return res.json({ ok: true, state: getLrcStatePayload().state });
|
||||||
const hideDuration = typeof autoHideDuration === 'number' ? autoHideDuration : settings.autoHideDuration;
|
|
||||||
const msg = JSON.stringify({
|
const elapsed = Math.max(0, Math.min(Date.now() - lrcPlayback.anchor, lrcPlayback.endMs - lrcPlayback.anchor));
|
||||||
type: 'activePreset',
|
lrcPlayback.pausedElapsed = elapsed;
|
||||||
preset,
|
lrcPlayback.paused = true;
|
||||||
contentData,
|
clearLrcEndTimer();
|
||||||
autoHideDuration: hideDuration
|
broadcastLrc();
|
||||||
|
res.json({ ok: true, state: getLrcStatePayload().state });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/lrc/resume', (req, res) => {
|
||||||
|
if (!lrcPlayback) return fail(res, 409, '当前没有正在播放的 LRC 字幕');
|
||||||
|
if (!lrcPlayback.paused) return res.json({ ok: true, state: getLrcStatePayload().state });
|
||||||
|
|
||||||
|
const remaining = lrcPlayback.endMs - lrcPlayback.anchor;
|
||||||
|
const elapsed = Math.min(lrcPlayback.pausedElapsed, remaining);
|
||||||
|
lrcPlayback.anchor = Date.now() - elapsed;
|
||||||
|
lrcPlayback.endMs = lrcPlayback.anchor + remaining;
|
||||||
|
lrcPlayback.paused = false;
|
||||||
|
scheduleLrcEnd();
|
||||||
|
broadcastLrc();
|
||||||
|
res.json({ ok: true, state: getLrcStatePayload().state });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/lrc/stop', (req, res) => {
|
||||||
|
const stopped = stopLrc('stopped');
|
||||||
|
res.json({ ok: true, stopped });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/lrc/state', (req, res) => {
|
||||||
|
res.json(getLrcStatePayload().state);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/health', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
uptimeSeconds: Math.round(process.uptime()),
|
||||||
|
dataDir: DATA_DIR,
|
||||||
|
presets: stores.appearancePresets.list().length,
|
||||||
|
contentPresets: stores.contentPresets.list().length,
|
||||||
|
lrcPresets: stores.lrcPresets.list().length,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
wss.clients.forEach(client => {
|
|
||||||
if (client.readyState === WebSocket.OPEN) {
|
// ── WebSocket ─────────────────────────────────────────────────────────────────
|
||||||
client.send(msg);
|
|
||||||
|
wss.on('connection', (ws) => {
|
||||||
|
ws.send(JSON.stringify(getActivePayload()));
|
||||||
|
ws.send(JSON.stringify(getLrcStatePayload()));
|
||||||
|
|
||||||
|
ws.on('message', (raw) => {
|
||||||
|
let message;
|
||||||
|
try {
|
||||||
|
message = JSON.parse(String(raw));
|
||||||
|
} catch (_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!message || typeof message !== 'object') return;
|
||||||
|
|
||||||
|
// 客户端时钟校准:原样回传 t0,并附上服务器时间
|
||||||
|
if (message.type === 'clock') {
|
||||||
|
ws.send(JSON.stringify({ type: 'clock', t0: message.t0, serverNow: Date.now() }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (message.type === 'state?') {
|
||||||
|
ws.send(JSON.stringify(getActivePayload()));
|
||||||
|
ws.send(JSON.stringify(getLrcStatePayload()));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
|
// ── 404 / 错误处理 ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
app.use('/api', (req, res) => {
|
||||||
|
fail(res, 404, '接口不存在');
|
||||||
|
});
|
||||||
|
|
||||||
wss.on('connection', ws => {
|
app.use((err, req, res, next) => {
|
||||||
// send current active on connect
|
console.error('[server]', err);
|
||||||
ws.send(JSON.stringify({
|
if (res.headersSent) return next(err);
|
||||||
type: 'activePreset',
|
const status = err.type === 'entity.too.large' ? 413 : 400;
|
||||||
preset: getActivePreset(),
|
fail(res, status, err.message || '服务器错误');
|
||||||
contentData: getContentData(),
|
|
||||||
autoHideDuration: settings.autoHideDuration
|
|
||||||
}));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const PORT = process.env.PORT || 30001;
|
|
||||||
server.listen(PORT, () => {
|
server.listen(PORT, () => {
|
||||||
console.log(`Server listening on http://localhost:${PORT}`);
|
console.log(`Server listening on http://localhost:${PORT}`);
|
||||||
|
console.log(`Data dir: ${DATA_DIR}`);
|
||||||
console.log('Admin UI: /admin.html, Management: /manage.html, Widget: /widget.html');
|
console.log('Admin UI: /admin.html, Management: /manage.html, Widget: /widget.html');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
module.exports = { app, server, stores };
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
|
||||||
|
const {
|
||||||
|
parseLrc,
|
||||||
|
parseTimestamp,
|
||||||
|
buildTimeline,
|
||||||
|
isCreditLine,
|
||||||
|
normalizeLrcPreset,
|
||||||
|
DEFAULT_CREDIT_KEYWORDS,
|
||||||
|
} = require('../lib/lrc');
|
||||||
|
|
||||||
|
const SAMPLE = `[ti:测试曲目]
|
||||||
|
[ar:测试歌手]
|
||||||
|
[al:测试专辑]
|
||||||
|
[by:editor]
|
||||||
|
[offset:0]
|
||||||
|
[00:00.00]作词:甲
|
||||||
|
[00:00.50]作曲:乙
|
||||||
|
[00:01.00]第一句
|
||||||
|
[00:03.50]第二句
|
||||||
|
[00:06.00][00:09.00]重复副歌
|
||||||
|
[00:12.000]最后一句
|
||||||
|
`;
|
||||||
|
|
||||||
|
test('parseTimestamp 支持 mm:ss / mm:ss.xx / mm:ss.xxx', () => {
|
||||||
|
assert.equal(parseTimestamp('00:12'), 12);
|
||||||
|
assert.equal(parseTimestamp('01:02.5'), 62.5);
|
||||||
|
assert.equal(parseTimestamp('01:02.50'), 62.5);
|
||||||
|
assert.equal(parseTimestamp('01:02.500'), 62.5);
|
||||||
|
assert.equal(parseTimestamp('1:02:50'), 62.5);
|
||||||
|
assert.equal(parseTimestamp('abc'), null);
|
||||||
|
assert.equal(parseTimestamp('00:61'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parseLrc 提取元数据与时间戳歌词', () => {
|
||||||
|
const parsed = parseLrc(SAMPLE);
|
||||||
|
assert.equal(parsed.meta.ti, '测试曲目');
|
||||||
|
assert.equal(parsed.meta.ar, '测试歌手');
|
||||||
|
assert.equal(parsed.metaOffsetMs, 0);
|
||||||
|
assert.equal(parsed.lyricEntries.length, 7);
|
||||||
|
assert.deepEqual(parsed.lyricEntries.map((e) => e.time), [0, 0.5, 1, 3.5, 6, 9, 12]);
|
||||||
|
assert.equal(parsed.warnings.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parseLrc 清理增强型逐字时间戳', () => {
|
||||||
|
const parsed = parseLrc('[00:01.00]<00:01.00>你<00:01.50>好');
|
||||||
|
assert.equal(parsed.lyricEntries[0].text, '你好');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parseLrc 保留增强型逐字片段', () => {
|
||||||
|
const parsed = parseLrc('[00:01.00]<00:01.00>Hello <00:01.50>world');
|
||||||
|
const entry = parsed.lyricEntries[0];
|
||||||
|
assert.equal(entry.text, 'Hello world');
|
||||||
|
assert.equal(entry.segments.length, 2);
|
||||||
|
assert.equal(entry.segments[0].text, 'Hello ');
|
||||||
|
assert.equal(entry.segments[0].time, 1);
|
||||||
|
assert.equal(entry.segments[1].text, 'world');
|
||||||
|
assert.equal(entry.segments[1].time, 1.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildTimeline 输出相对 cue 的逐字时间轴', () => {
|
||||||
|
const parsed = parseLrc('[00:10.00]<00:10.00>逐<00:10.50>字<00:11.00>测试');
|
||||||
|
const timeline = buildTimeline(parsed, { offsetMs: 0, range: { startIndex: 0, endIndex: null } });
|
||||||
|
assert.equal(timeline.cues[0].text, '逐字测试');
|
||||||
|
assert.deepEqual(timeline.cues[0].segments.map((s) => s.at), [0, 500, 1000]);
|
||||||
|
assert.equal(timeline.stats.karaokeCues, 1);
|
||||||
|
|
||||||
|
const shifted = buildTimeline(parsed, { offsetMs: 200, range: { startIndex: 0, endIndex: null } });
|
||||||
|
assert.deepEqual(shifted.cues[0].segments.map((s) => s.at), [200, 700, 1200]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('一行多时间戳时退回整句,避免逐字时间错位', () => {
|
||||||
|
const parsed = parseLrc('[00:01.00][00:20.00]<00:01.00>AB<00:01.50>CD');
|
||||||
|
assert.equal(parsed.lyricEntries[0].segments, null);
|
||||||
|
assert.equal(parsed.lyricEntries[1].segments, null);
|
||||||
|
assert.equal(parsed.lyricEntries[0].text, 'ABCD');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('同一时间点多行合并时退回整句点亮', () => {
|
||||||
|
const parsed = parseLrc('[00:01.00]<00:01.00>A<00:01.50>B\n[00:01.00]C');
|
||||||
|
const timeline = buildTimeline(parsed, {});
|
||||||
|
assert.equal(timeline.cues.length, 1);
|
||||||
|
assert.equal(timeline.cues[0].text, 'AB\nC');
|
||||||
|
assert.equal(timeline.cues[0].segments, null);
|
||||||
|
assert.equal(timeline.stats.karaokeCues, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('逐字片段可独立关闭,且自定义 CSS 会被保留', () => {
|
||||||
|
const preset = normalizeLrcPreset({
|
||||||
|
id: 'css-test',
|
||||||
|
source: '[00:01.00]<00:01.00>A<00:01.50>B',
|
||||||
|
style: {
|
||||||
|
animation: 'custom',
|
||||||
|
karaoke: false,
|
||||||
|
customCss: '.lrc-box { border: 1px solid red; }',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(preset.style.animation, 'custom');
|
||||||
|
assert.equal(preset.style.karaoke, false);
|
||||||
|
assert.match(preset.style.customCss, /border: 1px solid red/);
|
||||||
|
|
||||||
|
const longCss = normalizeLrcPreset({
|
||||||
|
id: 'css-long',
|
||||||
|
source: '',
|
||||||
|
style: { customCss: 'x'.repeat(60000), animation: 'not-a-real-animation' },
|
||||||
|
});
|
||||||
|
assert.equal(longCss.style.customCss.length, 50000);
|
||||||
|
assert.equal(longCss.style.animation, 'fade');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parseLrc 处理 offset 元数据与无时间戳行', () => {
|
||||||
|
const parsed = parseLrc('[offset:+250]\n没有时间戳的标题\n[00:01.00]歌词');
|
||||||
|
assert.equal(parsed.metaOffsetMs, 250);
|
||||||
|
assert.equal(parsed.lines.some((l) => l.kind === 'untimed'), true);
|
||||||
|
assert.equal(parsed.lyricEntries.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('isCreditLine 识别版权 / 制作信息但保留正常歌词', () => {
|
||||||
|
assert.equal(isCreditLine('作词:某人', DEFAULT_CREDIT_KEYWORDS), true);
|
||||||
|
assert.equal(isCreditLine(' [制作人] 某某', DEFAULT_CREDIT_KEYWORDS), true);
|
||||||
|
assert.equal(isCreditLine('© 2024 Example Studio', DEFAULT_CREDIT_KEYWORDS), true);
|
||||||
|
assert.equal(isCreditLine('This Song (Produced by X)', DEFAULT_CREDIT_KEYWORDS), true);
|
||||||
|
assert.equal(isCreditLine('第一句歌词', DEFAULT_CREDIT_KEYWORDS), false);
|
||||||
|
assert.equal(isCreditLine('我写了这首歌的作词部分作为纪念,但这句是很长的歌词不应该被过滤', DEFAULT_CREDIT_KEYWORDS), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildTimeline 过滤版权行并把第一句归零(自动偏移)', () => {
|
||||||
|
const parsed = parseLrc(SAMPLE);
|
||||||
|
const timeline = buildTimeline(parsed, {
|
||||||
|
filters: { dropCreditLines: true, creditKeywords: DEFAULT_CREDIT_KEYWORDS },
|
||||||
|
range: { startIndex: 0, endIndex: null },
|
||||||
|
offsetMs: 0,
|
||||||
|
tailMs: 4000,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(timeline.stats.excludedCredit, 2);
|
||||||
|
assert.equal(timeline.cues.length, 5);
|
||||||
|
assert.equal(timeline.cues[0].text, '第一句');
|
||||||
|
assert.equal(timeline.cues[0].t, 0);
|
||||||
|
assert.equal(timeline.cues[1].t, 2500);
|
||||||
|
assert.equal(timeline.cues[2].t, 5000);
|
||||||
|
assert.equal(timeline.cues[3].t, 8000);
|
||||||
|
assert.equal(timeline.cues[4].t, 11000);
|
||||||
|
assert.equal(timeline.endMs, 15000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildTimeline 支持范围选择与手动偏移', () => {
|
||||||
|
const parsed = parseLrc(SAMPLE);
|
||||||
|
const timeline = buildTimeline(parsed, {
|
||||||
|
filters: { dropCreditLines: true, creditKeywords: DEFAULT_CREDIT_KEYWORDS },
|
||||||
|
range: { startIndex: 1, endIndex: 2 },
|
||||||
|
offsetMs: 300,
|
||||||
|
tailMs: 2000,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(timeline.cues.length, 2);
|
||||||
|
assert.equal(timeline.cues[0].text, '第二句');
|
||||||
|
assert.equal(timeline.cues[0].t, 300); // 首句也应用手动偏移
|
||||||
|
assert.equal(timeline.cues[1].text, '重复副歌');
|
||||||
|
assert.equal(timeline.cues[1].t, 2800);
|
||||||
|
assert.equal(timeline.endMs, 4800);
|
||||||
|
assert.deepEqual(timeline.range, { startIndex: 1, endIndex: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildTimeline 合并同一时间点的多行(双语歌词)', () => {
|
||||||
|
const parsed = parseLrc('[00:01.00]Hello\n[00:01.00]你好\n[00:03.00]World');
|
||||||
|
const timeline = buildTimeline(parsed, {});
|
||||||
|
assert.equal(timeline.cues.length, 2);
|
||||||
|
assert.equal(timeline.cues[0].text, 'Hello\n你好');
|
||||||
|
assert.equal(timeline.cues[1].t, 2000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildTimeline 应用 LRC offset 元数据(正值提前)', () => {
|
||||||
|
const parsed = parseLrc('[offset:+500]\n[00:02.00]A\n[00:04.00]B');
|
||||||
|
const timeline = buildTimeline(parsed, { offsetMs: 0 });
|
||||||
|
assert.equal(timeline.metaOffsetMs, 500);
|
||||||
|
assert.equal(timeline.cues[0].t, 0);
|
||||||
|
assert.equal(timeline.cues[1].t, 1500);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizeLrcPreset 约束字段范围并保留数据', () => {
|
||||||
|
const preset = normalizeLrcPreset({
|
||||||
|
id: 'x1',
|
||||||
|
name: ' 测试字幕 ',
|
||||||
|
source: '[00:01.00]A',
|
||||||
|
filters: { creditKeywords: ['作词', '作词', ' 作曲 '] },
|
||||||
|
range: { startIndex: 5, endIndex: 2 },
|
||||||
|
offsetMs: 999999,
|
||||||
|
tailMs: -5,
|
||||||
|
style: { fontSize: 999, position: 'somewhere', align: 'center' },
|
||||||
|
});
|
||||||
|
assert.equal(preset.id, 'x1');
|
||||||
|
assert.equal(preset.name, '测试字幕');
|
||||||
|
assert.deepEqual(preset.filters.creditKeywords, ['作词', '作曲']);
|
||||||
|
assert.deepEqual(preset.range, { startIndex: 0, endIndex: 0 });
|
||||||
|
assert.equal(preset.offsetMs, 60000);
|
||||||
|
assert.equal(preset.tailMs, 0);
|
||||||
|
assert.equal(preset.style.fontSize, 200);
|
||||||
|
assert.equal(preset.style.position, 'bottom');
|
||||||
|
assert.equal(preset.style.align, 'center');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizeStyle 支持禁用背景 / 阴影 / 逐字', () => {
|
||||||
|
const preset = normalizeLrcPreset({
|
||||||
|
id: 'toggles',
|
||||||
|
source: '[00:01.00]A',
|
||||||
|
style: {
|
||||||
|
backgroundEnabled: false,
|
||||||
|
textShadowEnabled: false,
|
||||||
|
karaoke: false,
|
||||||
|
karaokePendingColor: 'rgba(255, 0, 0, 0.3)',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(preset.style.backgroundEnabled, false);
|
||||||
|
assert.equal(preset.style.textShadowEnabled, false);
|
||||||
|
assert.equal(preset.style.karaoke, false);
|
||||||
|
assert.equal(preset.style.karaokePendingColor, 'rgba(255, 0, 0, 0.3)');
|
||||||
|
// 未提供时默认开启
|
||||||
|
const defaults = normalizeLrcPreset({ id: 'defaults', source: '[00:01.00]A' });
|
||||||
|
assert.equal(defaults.style.backgroundEnabled, true);
|
||||||
|
assert.equal(defaults.style.textShadowEnabled, true);
|
||||||
|
assert.equal(defaults.style.karaoke, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizeStyle 支持入场时长 / 出场 / 回缩参数', () => {
|
||||||
|
const preset = normalizeLrcPreset({
|
||||||
|
id: 'durations',
|
||||||
|
source: '[00:01.00]A',
|
||||||
|
style: {
|
||||||
|
animation: 'blur',
|
||||||
|
enterDurationMs: 1500,
|
||||||
|
outro: 'blur',
|
||||||
|
outDurationMs: 800,
|
||||||
|
holdShrinkTo: 0.94,
|
||||||
|
shrinkDurationMs: 2500,
|
||||||
|
blurPx: 24,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(preset.style.animation, 'blur');
|
||||||
|
assert.equal(preset.style.enterDurationMs, 1500);
|
||||||
|
assert.equal(preset.style.outro, 'blur');
|
||||||
|
assert.equal(preset.style.outDurationMs, 800);
|
||||||
|
assert.equal(preset.style.holdShrinkTo, 0.94);
|
||||||
|
assert.equal(preset.style.shrinkDurationMs, 2500);
|
||||||
|
assert.equal(preset.style.blurPx, 24);
|
||||||
|
|
||||||
|
// 超界值被收敛
|
||||||
|
const clamped = normalizeLrcPreset({
|
||||||
|
id: 'clamped',
|
||||||
|
source: '',
|
||||||
|
style: { enterDurationMs: -100, outDurationMs: 999999, holdShrinkTo: 5, shrinkDurationMs: -1, blurPx: 900 },
|
||||||
|
});
|
||||||
|
assert.equal(clamped.style.enterDurationMs, 0);
|
||||||
|
assert.equal(clamped.style.outDurationMs, 10000);
|
||||||
|
assert.equal(clamped.style.holdShrinkTo, 1);
|
||||||
|
assert.equal(clamped.style.shrinkDurationMs, 0);
|
||||||
|
assert.equal(clamped.style.blurPx, 60);
|
||||||
|
|
||||||
|
// 非法枚举回退默认
|
||||||
|
const fallback = normalizeLrcPreset({ id: 'fallback', source: '', style: { outro: 'spin' } });
|
||||||
|
assert.equal(fallback.style.outro, 'fade');
|
||||||
|
assert.equal(fallback.style.enterDurationMs, 300);
|
||||||
|
assert.equal(fallback.style.outDurationMs, 260);
|
||||||
|
assert.equal(fallback.style.holdShrinkTo, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const { createStores } = require('../lib/store');
|
||||||
|
const models = require('../lib/models');
|
||||||
|
const { normalizeLrcPreset, DEFAULT_CREDIT_KEYWORDS } = require('../lib/lrc');
|
||||||
|
|
||||||
|
function makeTempDir() {
|
||||||
|
return fs.mkdtempSync(path.join(os.tmpdir(), 'obs-lt-store-'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeStores(dir) {
|
||||||
|
return createStores(dir, {
|
||||||
|
appearancePresets: [{
|
||||||
|
id: 'ap-1',
|
||||||
|
name: 'seed appearance',
|
||||||
|
kind: 'iframe',
|
||||||
|
align: 'right',
|
||||||
|
html: '<div>{{title}}</div>',
|
||||||
|
fieldDefs: [{ key: 'title', label: '标题', defaultValue: 'hello' }],
|
||||||
|
}],
|
||||||
|
contentPresets: [{
|
||||||
|
id: 'cp-1',
|
||||||
|
name: 'seed content',
|
||||||
|
appearancePresetId: 'ap-1',
|
||||||
|
fields: { title: 'world' },
|
||||||
|
}],
|
||||||
|
lrcPresets: [{
|
||||||
|
id: 'lrc-1',
|
||||||
|
name: 'seed lrc',
|
||||||
|
source: '[00:01.00]A\n[00:03.00]B',
|
||||||
|
filters: { dropCreditLines: true, dropUntimed: true, creditKeywords: DEFAULT_CREDIT_KEYWORDS },
|
||||||
|
range: { startIndex: 0, endIndex: null },
|
||||||
|
offsetMs: 0,
|
||||||
|
tailMs: 4000,
|
||||||
|
style: {},
|
||||||
|
}],
|
||||||
|
settings: { autoHideDuration: 0 },
|
||||||
|
normalizeAppearancePreset: models.normalizeAppearancePreset,
|
||||||
|
normalizeContentPreset: models.normalizeContentPreset,
|
||||||
|
normalizeLrcPreset,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('首次启动写入种子数据,重启后数据保持不变', () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
try {
|
||||||
|
const stores = makeStores(dir);
|
||||||
|
assert.equal(stores.appearancePresets.list().length, 1);
|
||||||
|
assert.equal(stores.contentPresets.list().length, 1);
|
||||||
|
assert.equal(stores.lrcPresets.list().length, 1);
|
||||||
|
assert.equal(stores.settings.value.autoHideDuration, 0);
|
||||||
|
|
||||||
|
for (const name of ['appearance-presets.json', 'content-presets.json', 'lrc-presets.json', 'settings.json']) {
|
||||||
|
assert.equal(fs.existsSync(path.join(dir, name)), true, name + ' should exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
const inserted = stores.lrcPresets.insert({
|
||||||
|
name: '新增 LRC',
|
||||||
|
source: '[00:02.00]第一句\n[00:05.00]第二句',
|
||||||
|
filters: { dropCreditLines: true, dropUntimed: true },
|
||||||
|
range: { startIndex: 0, endIndex: 0 },
|
||||||
|
offsetMs: 120,
|
||||||
|
tailMs: 2000,
|
||||||
|
style: { fontSize: 50 },
|
||||||
|
});
|
||||||
|
assert.ok(inserted.id);
|
||||||
|
stores.settings.update({ autoHideDuration: 4500 });
|
||||||
|
|
||||||
|
// 重新从磁盘加载,验证持久化
|
||||||
|
const reloaded = makeStores(dir);
|
||||||
|
const found = reloaded.lrcPresets.find(inserted.id);
|
||||||
|
assert.ok(found);
|
||||||
|
assert.equal(found.name, '新增 LRC');
|
||||||
|
assert.deepEqual(found.range, { startIndex: 0, endIndex: 0 });
|
||||||
|
assert.equal(found.offsetMs, 120);
|
||||||
|
assert.equal(found.tailMs, 2000);
|
||||||
|
assert.equal(found.style.fontSize, 50);
|
||||||
|
assert.equal(reloaded.settings.value.autoHideDuration, 4500);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('数据损坏时备份为 .bak 并用种子重建', () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
try {
|
||||||
|
makeStores(dir);
|
||||||
|
const file = path.join(dir, 'lrc-presets.json');
|
||||||
|
fs.writeFileSync(file, '{ this is not json', 'utf8');
|
||||||
|
|
||||||
|
const stores = makeStores(dir);
|
||||||
|
assert.equal(stores.lrcPresets.list().length, 1);
|
||||||
|
assert.equal(stores.lrcPresets.list()[0].id, 'lrc-1');
|
||||||
|
|
||||||
|
const backups = fs.readdirSync(dir).filter((name) => name.includes('.corrupt-') && name.endsWith('.bak'));
|
||||||
|
assert.equal(backups.length, 1);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('更新与删除会立即落盘且不留下临时文件', () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
try {
|
||||||
|
const stores = makeStores(dir);
|
||||||
|
const updated = stores.contentPresets.update('cp-1', { name: '改过的内容', fields: { title: 'changed' } });
|
||||||
|
assert.equal(updated.name, '改过的内容');
|
||||||
|
|
||||||
|
const afterUpdate = makeStores(dir);
|
||||||
|
assert.equal(afterUpdate.contentPresets.find('cp-1').name, '改过的内容');
|
||||||
|
|
||||||
|
assert.equal(stores.appearancePresets.remove('ap-1'), true);
|
||||||
|
const afterDelete = makeStores(dir);
|
||||||
|
assert.equal(afterDelete.appearancePresets.find('ap-1'), null);
|
||||||
|
|
||||||
|
const leftovers = fs.readdirSync(dir).filter((name) => name.endsWith('.tmp'));
|
||||||
|
assert.deepEqual(leftovers, []);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('写入时会规整非法字段(不会原样落盘)', () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
try {
|
||||||
|
const stores = makeStores(dir);
|
||||||
|
const inserted = stores.lrcPresets.insert({ name: '', source: 123, offsetMs: 'abc', style: { fontSize: 999 } });
|
||||||
|
assert.equal(inserted.source, '');
|
||||||
|
assert.equal(inserted.name, '未命名 LRC 字幕');
|
||||||
|
assert.equal(inserted.offsetMs, 0);
|
||||||
|
assert.equal(inserted.style.fontSize, 200);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user