Files
obs-lowerthird/lib/lrc.js
T
2026-11-11 21:40:57 +08:00

574 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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,
};