diff --git a/.gitignore b/.gitignore index 3c45938..a3e6056 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ node_modules/ *.log .DS_Store + +# 运行时数据(预设 / 设置 / LRC),由服务器自动创建,不提交到仓库 +data/ +data-test/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..65c294f --- /dev/null +++ b/README.md @@ -0,0 +1,232 @@ +# OBS Lower Third · LRC 字幕 + +OBS 浏览器源用的「下三分之一条 + LRC 字幕」管理系统。 + +- **外观预设**:自定义 HTML/CSS 模板,用 `{{字段名}}` 占位。 +- **内容预设**:把具体文字填入外观预设,激活后显示在 OBS 中。 +- **LRC 字幕(新增)**:导入 LRC、过滤版权/制作信息、自由选择起止句,打点后第一句立即出现,后续严格按 LRC 时间轴显示。 +- **持久化**:所有预设、LRC、设置保存在 `data/` 下的 JSON 文件里,不再写死在源代码中。 + +--- + +## 快速开始 + +```bash +npm install +npm start +``` + +默认端口 `30001`: + +| 页面 | 地址 | 用途 | +| --- | --- | --- | +| 管理面板 | | 外观 / 内容 / LRC 预设,打点控制 | +| OBS 浏览器源 | | 添加到 OBS Browser Source | +| 旧版管理页 | | 兼容保留,仅管理外观预设 | + +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)** / 无。 +- 字号、字重、字间距、行高、文字颜色。 +- 字体:常用字体快捷选择 + 自定义 CSS `font-family`。注意 OBS 所在电脑需要安装对应字体,否则回退到系统字体。 +- 背景:支持 `rgba()` / `transparent`,可用「显示背景」开关一键禁用(保留颜色配置)。 +- 文字阴影:可编辑具体阴影,可用「文字阴影」开关一键禁用。 +- 「显示下一句」开关:关闭后不再提前显示下一句提示。 +- 「逐字点亮」开关 + 「未唱文字颜色」:增强型 LRC 逐字显示,唱到的字变为主色,未唱的字保持半透明;当前字额外带 `.is-current` 类可供自定义 CSS 使用。 +- 一行多时间戳(副歌复用)或同一时间点多行(双语)会自动退回整句显示,避免逐字时间错位。 +- 内边距、圆角、最大宽度、距画面边缘距离、下一句缩放/颜色。 +- **自定义 CSS**:见下一节。 + +右侧有 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 字幕是独立图层,可以同时显示;「清空显示」会同时隐藏两者。 diff --git a/lib/lrc.js b/lib/lrc.js new file mode 100644 index 0000000..a919c50 --- /dev/null +++ b/lib/lrc.js @@ -0,0 +1,556 @@ +'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 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', + // 自定义 CSS / 自定义动画:作用于 .lrc-layer / .lrc-box / .lrc-text / .lrc-word + customCss: '', + showNextLine: true, + nextLineColor: 'rgba(255, 255, 255, 0.55)', + nextLineScale: 0.68, + bottomOffsetVh: 7, + // 逐字:仅对含增强型 标签的行生效 + 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(); +} + +/** + * 解析增强型逐字标签:文字 + * 返回纯文本 + 逐字片段(片段 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, metaOffsetMs: number, + * lines: Array, lyricEntries: Array, + * 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 (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.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, + MAX_SOURCE_CHARS, + parseLrc, + parseTimestamp, + buildTimeline, + isCreditLine, + normalizeFilters, + normalizeRange, + normalizeStyle, + normalizeLrcPreset, + normalizeKeywordList, + clampNumber, +}; diff --git a/lib/models.js b/lib/models.js new file mode 100644 index 0000000..728b60a --- /dev/null +++ b/lib/models.js @@ -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, +}; diff --git a/lib/seed.js b/lib/seed.js new file mode 100644 index 0000000..85684a0 --- /dev/null +++ b/lib/seed.js @@ -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 }; diff --git a/lib/store.js b/lib/store.js new file mode 100644 index 0000000..e14fc16 --- /dev/null +++ b/lib/store.js @@ -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, +}; diff --git a/package.json b/package.json index 0af5f74..6040b4e 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,10 @@ { "name": "obs-lowerthird", "version": "1.0.0", - "description": "", + "description": "OBS 下三分之一条与 LRC 字幕管理系统(JSON 持久化)", "main": "server.js", "scripts": { - "test": "echo \"No tests configured\"", + "test": "node --test", "start": "node server.js" }, "keywords": [], diff --git a/public/admin.html b/public/admin.html index a4f2cd4..8d71a05 100644 --- a/public/admin.html +++ b/public/admin.html @@ -91,8 +91,9 @@
✨ 新版管理界面已上线! - 支持内容/外观预设分离、占位符、键盘快捷键、自动隐藏等功能。 + 支持内容/外观预设分离、LRC 字幕、打点播放、占位符、键盘快捷键、自动隐藏等功能。 → 前往新版管理页 + LRC 字幕

OBS 节目信息下三分之一条 - 预设管理

1. 在 OBS 中添加 Browser Source,URL 指向 http://本机或服务器/widget.html
diff --git a/public/lrc.css b/public/lrc.css new file mode 100644 index 0000000..9ebe426 --- /dev/null +++ b/public/lrc.css @@ -0,0 +1,60 @@ +/* LRC 字幕运行时样式:管理页预览与 OBS widget 共用 */ + +/* ── 进场动画 ───────────────────────────────────────────────────────────── */ +.lrc-anim-fade .lrc-text { + animation: lrcFadeIn 0.22s ease both; +} +.lrc-anim-slide .lrc-text { + animation: lrcSlideIn 0.24s cubic-bezier(0.2, 0.8, 0.3, 1) both; +} +.lrc-anim-zoom .lrc-text { + animation: lrcZoomIn 0.26s cubic-bezier(0.2, 0.9, 0.3, 1.15) both; +} +.lrc-anim-blur .lrc-text { + animation: lrcBlurIn 0.3s ease both; +} +.lrc-anim-bounce .lrc-text { + animation: lrcBounceIn 0.42s cubic-bezier(0.2, 0.9, 0.3, 1.2) both; +} +/* lrc-anim-custom:不内置动画,由「自定义 CSS」定义,例如: + .lrc-layer.lrc-anim-custom .lrc-text { animation: myAnim .5s ease both; } + @keyframes myAnim { from { opacity: 0; transform: translateY(18px) scale(.96); } } +*/ +.lrc-anim-none .lrc-text { + animation: 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 { + from { opacity: 0; filter: blur(10px); } + to { opacity: 1; filter: blur(0); } +} +@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); } +} + +/* ── 逐字(增强型 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 { + /* 默认与已唱字一致,仅作为自定义钩子 */ +} diff --git a/public/manage.html b/public/manage.html index d21f445..60b494f 100644 --- a/public/manage.html +++ b/public/manage.html @@ -4,12 +4,14 @@ OBS Lower Third · 管理 + + +

- +
+ +
+
+
+
+
+
+