@yoonion/mimi-seed-mcp 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/assets/agent-guide.md +4 -3
- package/dist/i18n/tools-en/video.d.ts +18 -0
- package/dist/i18n/tools-en/video.js +18 -0
- package/dist/lib/telegram-approval.d.ts +4 -2
- package/dist/lib/telegram-approval.js +165 -14
- package/dist/lib/telegram-relay.d.ts +93 -0
- package/dist/lib/telegram-relay.js +234 -0
- package/dist/registers/video.js +78 -2
- package/dist/video/clips.d.ts +183 -0
- package/dist/video/clips.js +457 -0
- package/dist/video/narration.d.ts +110 -0
- package/dist/video/narration.js +326 -0
- package/dist/video/project.d.ts +1 -1
- package/dist/video/project.js +7 -4
- package/dist/video/providers.d.ts +3 -2
- package/dist/video/providers.js +3 -3
- package/dist/video/render.d.ts +7 -0
- package/dist/video/render.js +50 -3
- package/dist/video/schemas.d.ts +1 -0
- package/dist/video/schemas.js +1 -0
- package/dist/video/types.d.ts +2 -0
- package/dist/video/windows-voice.d.ts +22 -0
- package/dist/video/windows-voice.js +143 -0
- package/npm-shrinkwrap.json +5 -5
- package/package.json +1 -1
- package/tool-manifest.json +12 -4
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// 내레이션 — 스토리보드 장면별 음성을 만들고, 장면 길이에 맞춰 한 트랙으로 합친다.
|
|
2
|
+
// 엔진: ElevenLabs (유료, 키 필요) 또는 Windows 기본 목소리 (무료, 키 없음, Windows 전용 — windows-voice.ts).
|
|
3
|
+
//
|
|
4
|
+
// 설계: docs/design/media-generation-providers.md §4.1.
|
|
5
|
+
// - 길이 기준은 스토리보드다. 음성이 장면보다 길면 늘이거나 자르지 않고 overruns 로 돌려준다.
|
|
6
|
+
// - 장면 음성은 (voiceId, modelId, text) 해시로 캐시한다. 이미 돈을 낸 장면은 다시 요청하지 않는다.
|
|
7
|
+
// - 키(ELEVENLABS_API_KEY)는 api.elevenlabs.io 에만 보낸다. 리디렉션은 따라가지 않는다.
|
|
8
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
9
|
+
import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { catalog } from '#core/lang.js';
|
|
13
|
+
import { fetchWithTimeout } from '../lib/http.js';
|
|
14
|
+
import { encodePathSegment } from '../lib/url-path.js';
|
|
15
|
+
import { readJson, writeJsonAtomic } from './files.js';
|
|
16
|
+
import { loadProject, registerAsset } from './project.js';
|
|
17
|
+
import { sanitizeExternalText } from './providers.js';
|
|
18
|
+
import { runFfmpeg } from './render.js';
|
|
19
|
+
import { listWindowsVoices, speakToWav, WINDOWS_VOICE } from './windows-voice.js';
|
|
20
|
+
const M = catalog({
|
|
21
|
+
envRequired: '❌ ELEVENLABS_API_KEY 환경변수가 필요합니다.',
|
|
22
|
+
apiFailed: (status, message) => `ElevenLabs 요청 실패 (${status}): ${message}`,
|
|
23
|
+
badResponse: 'ElevenLabs 응답 형식이 예상과 다릅니다.',
|
|
24
|
+
badAudio: 'ElevenLabs 응답이 유효한 20MB 이하 MP3가 아닙니다.',
|
|
25
|
+
noAlignment: 'ElevenLabs 응답에 음성 타이밍(alignment)이 없어 길이를 잴 수 없습니다.',
|
|
26
|
+
noNarration: '내레이션 문구가 있는 장면이 없습니다. video_save_plan 의 scenes[].narration 을 채우세요.',
|
|
27
|
+
license: 'ElevenLabs generated output; commercial use depends on the ElevenLabs plan and terms',
|
|
28
|
+
windowsLicense: 'Generated locally with a Windows built-in voice (System.Speech); check the Windows license terms before commercial use',
|
|
29
|
+
voiceRequired: '❌ ElevenLabs 엔진은 voiceId 가 필요합니다. video_list_voices 로 고르세요.',
|
|
30
|
+
badVoice: (engine) => `❌ ${engine} 엔진에 맞지 않는 voiceId 입니다. video_list_voices 로 고르세요.`,
|
|
31
|
+
next: 'video_build_timeline 에 narrationAssetId 로 넘기세요. 타임라인 장면 길이는 프로젝트 장면 길이와 같게 두세요.',
|
|
32
|
+
}, {
|
|
33
|
+
envRequired: '❌ The ELEVENLABS_API_KEY environment variable is required.',
|
|
34
|
+
apiFailed: (status, message) => `ElevenLabs request failed (${status}): ${message}`,
|
|
35
|
+
badResponse: 'The ElevenLabs response has an unexpected shape.',
|
|
36
|
+
badAudio: 'The ElevenLabs response is not a valid MP3 of 20MB or less.',
|
|
37
|
+
noAlignment: 'The ElevenLabs response has no timing (alignment), so its length cannot be measured.',
|
|
38
|
+
noNarration: 'No scene has narration text. Fill scenes[].narration with video_save_plan.',
|
|
39
|
+
license: 'ElevenLabs generated output; commercial use depends on the ElevenLabs plan and terms',
|
|
40
|
+
windowsLicense: 'Generated locally with a Windows built-in voice (System.Speech); check the Windows license terms before commercial use',
|
|
41
|
+
voiceRequired: '❌ The ElevenLabs engine needs a voiceId. Pick one with video_list_voices.',
|
|
42
|
+
badVoice: (engine) => `❌ That voiceId does not fit the ${engine} engine. Pick one with video_list_voices.`,
|
|
43
|
+
next: 'Pass it to video_build_timeline as narrationAssetId. Keep the timeline scene durations equal to the project scenes.',
|
|
44
|
+
});
|
|
45
|
+
const API = 'https://api.elevenlabs.io';
|
|
46
|
+
export const DEFAULT_TTS_MODEL = 'eleven_multilingual_v2';
|
|
47
|
+
const OUTPUT_FORMAT = 'mp3_44100_128';
|
|
48
|
+
const MAX_AUDIO_BYTES = 20 * 1024 * 1024;
|
|
49
|
+
/** 음성이 장면보다 이만큼까지 길어도 허용한다 — 문장 끝 숨소리 정도. */
|
|
50
|
+
const OVERRUN_TOLERANCE_SEC = 0.05;
|
|
51
|
+
export const VOICE_ID = /^[A-Za-z0-9]{1,64}$/;
|
|
52
|
+
export const TTS_MODEL_ID = /^[a-z0-9_]{1,64}$/;
|
|
53
|
+
/** elevenlabs: 유료·키 필요 · windows: 이 컴퓨터의 기본 목소리 (무료, 키 없음, Windows 전용) */
|
|
54
|
+
export const NARRATION_ENGINES = ['elevenlabs', 'windows'];
|
|
55
|
+
function apiKey() {
|
|
56
|
+
const value = process.env.ELEVENLABS_API_KEY?.trim();
|
|
57
|
+
if (!value)
|
|
58
|
+
throw new Error(M().envRequired);
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
async function callElevenLabs(url, init) {
|
|
62
|
+
const response = await fetchWithTimeout(url, {
|
|
63
|
+
...init,
|
|
64
|
+
// 키를 다른 호스트로 들고 가지 않게 리디렉션은 실패로 본다.
|
|
65
|
+
redirect: 'error',
|
|
66
|
+
headers: { 'xi-api-key': apiKey(), Accept: 'application/json', ...(init.headers ?? {}) },
|
|
67
|
+
});
|
|
68
|
+
const text = await response.text();
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
throw new Error(M().apiFailed(response.status, sanitizeExternalText(text, 500)));
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(text);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
throw new Error(M().badResponse, { cause: error });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// ── voices ────────────────────────────────────────────────────────────────
|
|
80
|
+
const voicesResponse = z.object({
|
|
81
|
+
voices: z.array(z.object({
|
|
82
|
+
voice_id: z.string(),
|
|
83
|
+
name: z.string().nullish(),
|
|
84
|
+
category: z.string().nullish(),
|
|
85
|
+
labels: z.record(z.string(), z.string()).nullish(),
|
|
86
|
+
description: z.string().nullish(),
|
|
87
|
+
preview_url: z.string().nullish(),
|
|
88
|
+
})),
|
|
89
|
+
has_more: z.boolean().optional(),
|
|
90
|
+
next_page_token: z.string().nullish(),
|
|
91
|
+
});
|
|
92
|
+
export async function listVoices(input) {
|
|
93
|
+
if (input.engine === 'windows') {
|
|
94
|
+
const needle = input.search?.toLowerCase();
|
|
95
|
+
const voices = (await listWindowsVoices())
|
|
96
|
+
.filter((v) => !needle || `${v.name} ${v.culture} ${v.gender}`.toLowerCase().includes(needle));
|
|
97
|
+
return { engine: 'windows', voices, hasMore: false };
|
|
98
|
+
}
|
|
99
|
+
const params = new URLSearchParams({ page_size: String(input.pageSize ?? 30) });
|
|
100
|
+
if (input.search)
|
|
101
|
+
params.set('search', input.search);
|
|
102
|
+
if (input.nextPageToken)
|
|
103
|
+
params.set('next_page_token', input.nextPageToken);
|
|
104
|
+
const parsed = voicesResponse.safeParse(await callElevenLabs(`${API}/v2/voices?${params}`, { method: 'GET' }));
|
|
105
|
+
if (!parsed.success)
|
|
106
|
+
throw new Error(M().badResponse);
|
|
107
|
+
return {
|
|
108
|
+
voices: parsed.data.voices.map((voice) => ({
|
|
109
|
+
voiceId: voice.voice_id,
|
|
110
|
+
name: sanitizeExternalText(voice.name ?? '', 200),
|
|
111
|
+
category: voice.category ?? undefined,
|
|
112
|
+
labels: Object.fromEntries(Object.entries(voice.labels ?? {})
|
|
113
|
+
.slice(0, 20)
|
|
114
|
+
.map(([key, value]) => [sanitizeExternalText(key, 50), sanitizeExternalText(value, 100)])),
|
|
115
|
+
description: voice.description ? sanitizeExternalText(voice.description, 500) : undefined,
|
|
116
|
+
previewUrl: voice.preview_url ?? undefined,
|
|
117
|
+
})),
|
|
118
|
+
hasMore: parsed.data.has_more ?? false,
|
|
119
|
+
nextPageToken: parsed.data.next_page_token ?? undefined,
|
|
120
|
+
untrustedExternalText: true,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const cacheMeta = z.object({ speechSec: z.number().finite().nonnegative(), voice: z.string().optional() });
|
|
124
|
+
function cacheDir(projectDir) {
|
|
125
|
+
return path.join(path.resolve(projectDir), 'assets', 'generated', 'narration-cache');
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* 네트워크 없이 계획만 세운다 — 미리보기와 실행이 같은 장면 선택·캐시 판단을 쓰게.
|
|
129
|
+
* 과금 근거는 캐시되지 않은 장면의 글자 수다 (ElevenLabs 는 글자 수로 과금한다).
|
|
130
|
+
*/
|
|
131
|
+
export function planNarration(input) {
|
|
132
|
+
const project = loadProject(input.projectDir);
|
|
133
|
+
const engine = input.engine ?? 'elevenlabs';
|
|
134
|
+
if (engine === 'elevenlabs') {
|
|
135
|
+
if (!input.voiceId)
|
|
136
|
+
throw new Error(M().voiceRequired);
|
|
137
|
+
if (!VOICE_ID.test(input.voiceId))
|
|
138
|
+
throw new Error(M().badVoice(engine));
|
|
139
|
+
}
|
|
140
|
+
else if (input.voiceId && !WINDOWS_VOICE.test(input.voiceId)) {
|
|
141
|
+
throw new Error(M().badVoice(engine));
|
|
142
|
+
}
|
|
143
|
+
// windows 는 모델이 없다. 목소리를 고르지 않았으면 '언어로 고름' 을 캐시 열쇠에 넣는다.
|
|
144
|
+
const modelId = engine === 'windows' ? 'system-speech' : input.modelId ?? DEFAULT_TTS_MODEL;
|
|
145
|
+
const voiceId = input.voiceId ?? (engine === 'windows' ? `auto:${project.language}` : '');
|
|
146
|
+
const extension = engine === 'windows' ? 'wav' : 'mp3';
|
|
147
|
+
const segments = [];
|
|
148
|
+
for (const scene of project.scenes) {
|
|
149
|
+
const text = scene.narration.trim();
|
|
150
|
+
if (!text)
|
|
151
|
+
continue;
|
|
152
|
+
// elevenlabs 는 예전 캐시 열쇠를 그대로 둔다 (이미 돈 낸 장면을 다시 요청하지 않게)
|
|
153
|
+
const key = engine === 'elevenlabs' ? [voiceId, modelId, text] : [engine, voiceId, modelId, text];
|
|
154
|
+
const hash = createHash('sha256').update(JSON.stringify(key)).digest('hex');
|
|
155
|
+
const audioPath = path.join(cacheDir(input.projectDir), `${hash}.${extension}`);
|
|
156
|
+
const metaPath = path.join(cacheDir(input.projectDir), `${hash}.json`);
|
|
157
|
+
segments.push({
|
|
158
|
+
sceneId: scene.id,
|
|
159
|
+
sceneSec: scene.durationSec,
|
|
160
|
+
text,
|
|
161
|
+
characters: [...text].length,
|
|
162
|
+
cached: existsSync(audioPath) && existsSync(metaPath),
|
|
163
|
+
audioPath,
|
|
164
|
+
metaPath,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
if (segments.length === 0)
|
|
168
|
+
throw new Error(M().noNarration);
|
|
169
|
+
return {
|
|
170
|
+
engine,
|
|
171
|
+
voiceId,
|
|
172
|
+
modelId,
|
|
173
|
+
language: project.language,
|
|
174
|
+
segments,
|
|
175
|
+
// Windows 목소리는 돈이 들지 않는다
|
|
176
|
+
billableCharacters: engine === 'windows'
|
|
177
|
+
? 0
|
|
178
|
+
: segments.filter((s) => !s.cached).reduce((sum, s) => sum + s.characters, 0),
|
|
179
|
+
cachedScenes: segments.filter((s) => s.cached).length,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
const timestampsResponse = z.object({
|
|
183
|
+
audio_base64: z.string().min(1),
|
|
184
|
+
alignment: z.object({ character_end_times_seconds: z.array(z.number()) }).nullish(),
|
|
185
|
+
normalized_alignment: z.object({ character_end_times_seconds: z.array(z.number()) }).nullish(),
|
|
186
|
+
});
|
|
187
|
+
/** MP3 = ID3 태그 또는 MPEG 프레임 동기 (0xFFE). */
|
|
188
|
+
export function hasMp3Signature(bytes) {
|
|
189
|
+
if (bytes.length < 3)
|
|
190
|
+
return false;
|
|
191
|
+
if (bytes.subarray(0, 3).toString('ascii') === 'ID3')
|
|
192
|
+
return true;
|
|
193
|
+
return bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0;
|
|
194
|
+
}
|
|
195
|
+
/** 응답에서 음성 길이(마지막 글자의 끝 시각)를 뽑는다. */
|
|
196
|
+
export function speechSecondsFrom(body) {
|
|
197
|
+
const parsed = timestampsResponse.safeParse(body);
|
|
198
|
+
if (!parsed.success)
|
|
199
|
+
throw new Error(M().badResponse);
|
|
200
|
+
const bytes = Buffer.from(parsed.data.audio_base64, 'base64');
|
|
201
|
+
if (bytes.length === 0 || bytes.length > MAX_AUDIO_BYTES || !hasMp3Signature(bytes))
|
|
202
|
+
throw new Error(M().badAudio);
|
|
203
|
+
const ends = parsed.data.alignment?.character_end_times_seconds
|
|
204
|
+
?? parsed.data.normalized_alignment?.character_end_times_seconds;
|
|
205
|
+
if (!ends?.length)
|
|
206
|
+
throw new Error(M().noAlignment);
|
|
207
|
+
return { bytes, speechSec: Math.max(...ends) };
|
|
208
|
+
}
|
|
209
|
+
function writeFileAtomic(destination, bytes) {
|
|
210
|
+
const temp = `${destination}.${randomUUID()}.tmp`;
|
|
211
|
+
try {
|
|
212
|
+
writeFileSync(temp, bytes, { flag: 'wx' });
|
|
213
|
+
renameSync(temp, destination);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
try {
|
|
217
|
+
unlinkSync(temp);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// 임시 파일이 만들어지기 전에 실패했을 수 있다 — 원래 오류를 그대로 던진다.
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async function synthesize(segment, voiceId, modelId) {
|
|
226
|
+
const url = `${API}/v1/text-to-speech/${encodePathSegment(voiceId)}/with-timestamps?output_format=${OUTPUT_FORMAT}`;
|
|
227
|
+
const body = await callElevenLabs(url, {
|
|
228
|
+
method: 'POST',
|
|
229
|
+
headers: { 'Content-Type': 'application/json' },
|
|
230
|
+
body: JSON.stringify({ text: segment.text, model_id: modelId }),
|
|
231
|
+
});
|
|
232
|
+
const { bytes, speechSec } = speechSecondsFrom(body);
|
|
233
|
+
mkdirSync(path.dirname(segment.audioPath), { recursive: true });
|
|
234
|
+
writeFileAtomic(segment.audioPath, bytes);
|
|
235
|
+
// 메타는 오디오 다음에 쓴다 — 둘 다 있어야 캐시로 인정되므로, 중간에 죽으면 다음 호출이 다시 만든다.
|
|
236
|
+
writeJsonAtomic(segment.metaPath, { speechSec });
|
|
237
|
+
return speechSec;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* 장면별 음성을 장면 길이만큼 무음으로 채워 이어 붙이는 FFmpeg 인자.
|
|
241
|
+
* 내레이션이 없는 장면은 anullsrc 무음으로 자리를 채운다.
|
|
242
|
+
*/
|
|
243
|
+
export function buildNarrationMixArgs(scenes, outputPath) {
|
|
244
|
+
const inputs = [];
|
|
245
|
+
const filters = [];
|
|
246
|
+
let inputIndex = 0;
|
|
247
|
+
scenes.forEach((scene, index) => {
|
|
248
|
+
if (scene.audioPath) {
|
|
249
|
+
inputs.push('-i', scene.audioPath);
|
|
250
|
+
filters.push(`[${inputIndex}:a]aformat=sample_rates=44100:channel_layouts=stereo,apad,` +
|
|
251
|
+
`atrim=0:${scene.sceneSec},asetpts=PTS-STARTPTS[s${index}]`);
|
|
252
|
+
inputIndex += 1;
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
filters.push(`anullsrc=r=44100:cl=stereo,atrim=0:${scene.sceneSec},asetpts=PTS-STARTPTS[s${index}]`);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
filters.push(`${scenes.map((_, index) => `[s${index}]`).join('')}concat=n=${scenes.length}:v=0:a=1[out]`);
|
|
259
|
+
return [...inputs, '-filter_complex', filters.join(';'), '-map', '[out]', '-c:a', 'aac', '-b:a', '192k', outputPath];
|
|
260
|
+
}
|
|
261
|
+
export async function generateNarration(input) {
|
|
262
|
+
const plan = planNarration(input);
|
|
263
|
+
const project = loadProject(input.projectDir);
|
|
264
|
+
const usedVoices = new Set();
|
|
265
|
+
const speech = new Map();
|
|
266
|
+
const results = [];
|
|
267
|
+
for (const segment of plan.segments) {
|
|
268
|
+
let speechSec;
|
|
269
|
+
if (segment.cached) {
|
|
270
|
+
const meta = cacheMeta.parse(readJson(segment.metaPath));
|
|
271
|
+
speechSec = meta.speechSec;
|
|
272
|
+
if (meta.voice)
|
|
273
|
+
usedVoices.add(meta.voice);
|
|
274
|
+
}
|
|
275
|
+
else if (plan.engine === 'windows') {
|
|
276
|
+
const made = await speakToWav(segment.text, segment.audioPath, {
|
|
277
|
+
voice: input.voiceId,
|
|
278
|
+
lang: plan.language,
|
|
279
|
+
});
|
|
280
|
+
speechSec = made.speechSec;
|
|
281
|
+
if (made.voice)
|
|
282
|
+
usedVoices.add(made.voice);
|
|
283
|
+
writeJsonAtomic(segment.metaPath, { speechSec, voice: made.voice });
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
speechSec = await synthesize(segment, plan.voiceId, plan.modelId);
|
|
287
|
+
}
|
|
288
|
+
speech.set(segment.sceneId, speechSec);
|
|
289
|
+
results.push({ sceneId: segment.sceneId, speechSec, sceneSec: segment.sceneSec, cached: segment.cached });
|
|
290
|
+
}
|
|
291
|
+
const overruns = results.filter((r) => r.speechSec > r.sceneSec + OVERRUN_TOLERANCE_SEC);
|
|
292
|
+
if (overruns.length) {
|
|
293
|
+
// 스토리보드가 기준이다 — 자르거나 늘리지 않고 에이전트가 문구나 장면 길이를 고치게 한다.
|
|
294
|
+
return { registered: false, overruns, segments: results };
|
|
295
|
+
}
|
|
296
|
+
const bySceneId = new Map(plan.segments.map((s) => [s.sceneId, s]));
|
|
297
|
+
const id = `narration-${randomUUID()}`;
|
|
298
|
+
const outputPath = path.join(path.resolve(input.projectDir), 'assets', 'generated', `${id}.m4a`);
|
|
299
|
+
mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
300
|
+
// 내레이션이 없는 장면도 자리를 무음으로 채워야 트랙 전체가 영상 장면 경계와 맞는다.
|
|
301
|
+
const args = buildNarrationMixArgs(project.scenes.map((scene) => ({
|
|
302
|
+
sceneSec: scene.durationSec,
|
|
303
|
+
audioPath: speech.has(scene.id) ? bySceneId.get(scene.id)?.audioPath : undefined,
|
|
304
|
+
})), outputPath);
|
|
305
|
+
await runFfmpeg(args, path.resolve(input.projectDir));
|
|
306
|
+
const asset = registerAsset(input.projectDir, {
|
|
307
|
+
id,
|
|
308
|
+
kind: 'audio',
|
|
309
|
+
sourceType: 'generated',
|
|
310
|
+
path: outputPath,
|
|
311
|
+
license: plan.engine === 'windows' ? M().windowsLicense : M().license,
|
|
312
|
+
attribution: plan.engine === 'windows'
|
|
313
|
+
? `Windows voice ${[...usedVoices].join(', ') || plan.voiceId}`
|
|
314
|
+
: `ElevenLabs voice ${plan.voiceId}`,
|
|
315
|
+
allowedForRendering: true,
|
|
316
|
+
provider: plan.engine === 'windows' ? 'windows:system-speech' : `elevenlabs:${plan.modelId}`,
|
|
317
|
+
prompt: plan.segments.map((s) => `[${s.sceneId}] ${s.text}`).join('\n'),
|
|
318
|
+
});
|
|
319
|
+
return {
|
|
320
|
+
registered: true,
|
|
321
|
+
asset,
|
|
322
|
+
totalDurationSec: project.scenes.reduce((sum, scene) => sum + scene.durationSec, 0),
|
|
323
|
+
segments: results,
|
|
324
|
+
next: M().next,
|
|
325
|
+
};
|
|
326
|
+
}
|
package/dist/video/project.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export interface AddLocalAssetInput {
|
|
|
46
46
|
attribution?: string;
|
|
47
47
|
}
|
|
48
48
|
export declare function addLocalAsset(input: AddLocalAssetInput): VideoAsset;
|
|
49
|
-
export declare function buildTimeline(projectDir: string, scenes: VideoTimelineScene[], audioAssetId?: string, captionStyle?: VideoCaptionStyle): VideoTimeline;
|
|
49
|
+
export declare function buildTimeline(projectDir: string, scenes: VideoTimelineScene[], audioAssetId?: string, captionStyle?: VideoCaptionStyle, narrationAssetId?: string): VideoTimeline;
|
|
50
50
|
export declare function loadTimeline(projectDir: string): VideoTimeline;
|
|
51
51
|
export declare const __testing: {
|
|
52
52
|
dimensions: typeof dimensions;
|
package/dist/video/project.js
CHANGED
|
@@ -277,7 +277,7 @@ export function addLocalAsset(input) {
|
|
|
277
277
|
allowedForRendering: true,
|
|
278
278
|
});
|
|
279
279
|
}
|
|
280
|
-
export function buildTimeline(projectDir, scenes, audioAssetId, captionStyle) {
|
|
280
|
+
export function buildTimeline(projectDir, scenes, audioAssetId, captionStyle, narrationAssetId) {
|
|
281
281
|
const dir = requireAbsolutePath(projectDir, 'projectDir');
|
|
282
282
|
const project = loadProject(dir);
|
|
283
283
|
const manifest = loadAssets(dir);
|
|
@@ -298,10 +298,12 @@ export function buildTimeline(projectDir, scenes, audioAssetId, captionStyle) {
|
|
|
298
298
|
throw new Error(M().sceneDuration(scene.id));
|
|
299
299
|
}
|
|
300
300
|
}
|
|
301
|
-
|
|
302
|
-
|
|
301
|
+
for (const audioId of [audioAssetId, narrationAssetId]) {
|
|
302
|
+
if (!audioId)
|
|
303
|
+
continue;
|
|
304
|
+
const audio = byId.get(audioId);
|
|
303
305
|
if (!audio || audio.kind !== 'audio' || !audio.allowedForRendering) {
|
|
304
|
-
throw new Error(M().badAudio(
|
|
306
|
+
throw new Error(M().badAudio(audioId));
|
|
305
307
|
}
|
|
306
308
|
}
|
|
307
309
|
const totalDurationSec = scenes.reduce((sum, scene) => sum + scene.durationSec, 0);
|
|
@@ -317,6 +319,7 @@ export function buildTimeline(projectDir, scenes, audioAssetId, captionStyle) {
|
|
|
317
319
|
totalDurationSec,
|
|
318
320
|
scenes,
|
|
319
321
|
audioAssetId,
|
|
322
|
+
narrationAssetId,
|
|
320
323
|
captionStyle,
|
|
321
324
|
}, M().timelineLabel);
|
|
322
325
|
writeJsonAtomic(path.join(dir, TIMELINE_FILE), timeline);
|
|
@@ -16,7 +16,7 @@ export interface YouTubeReference {
|
|
|
16
16
|
untrustedExternalText: true;
|
|
17
17
|
query: string;
|
|
18
18
|
}
|
|
19
|
-
declare function sanitizeExternalText(value: string | undefined, maxLength: number): string;
|
|
19
|
+
export declare function sanitizeExternalText(value: string | undefined, maxLength: number): string;
|
|
20
20
|
export interface ResearchYouTubeInput {
|
|
21
21
|
projectDir: string;
|
|
22
22
|
queries?: string[];
|
|
@@ -77,7 +77,8 @@ export interface SearchStockInput {
|
|
|
77
77
|
}
|
|
78
78
|
export declare function searchStock(input: SearchStockInput): Promise<PexelsVideoResult[]>;
|
|
79
79
|
declare function validatePexelsUrl(value: string): URL;
|
|
80
|
-
declare function
|
|
80
|
+
export declare function downloadLimited(response: Response, destination: string, maxBytes: number): Promise<void>;
|
|
81
|
+
export declare function hasMp4Signature(filePath: string): boolean;
|
|
81
82
|
export interface DownloadStockSelection {
|
|
82
83
|
id: number;
|
|
83
84
|
downloadUrl: string;
|
package/dist/video/providers.js
CHANGED
|
@@ -65,7 +65,7 @@ async function fetchJson(url, init) {
|
|
|
65
65
|
}
|
|
66
66
|
return body;
|
|
67
67
|
}
|
|
68
|
-
function sanitizeExternalText(value, maxLength) {
|
|
68
|
+
export function sanitizeExternalText(value, maxLength) {
|
|
69
69
|
// 제어문자 제거가 이 함수의 목적이다 — 정규식에 들어 있는 게 정상.
|
|
70
70
|
// eslint-disable-next-line no-control-regex
|
|
71
71
|
return (value ?? '').replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '').slice(0, maxLength);
|
|
@@ -211,7 +211,7 @@ async function fetchPexelsMedia(value) {
|
|
|
211
211
|
}
|
|
212
212
|
throw new Error(M().tooManyRedirects);
|
|
213
213
|
}
|
|
214
|
-
async function downloadLimited(response, destination, maxBytes) {
|
|
214
|
+
export async function downloadLimited(response, destination, maxBytes) {
|
|
215
215
|
if (!response.body)
|
|
216
216
|
throw new Error(M().noBody);
|
|
217
217
|
const tempPath = `${destination}.${randomUUID()}.tmp`;
|
|
@@ -249,7 +249,7 @@ async function downloadLimited(response, destination, maxBytes) {
|
|
|
249
249
|
reader.releaseLock();
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
|
-
function hasMp4Signature(filePath) {
|
|
252
|
+
export function hasMp4Signature(filePath) {
|
|
253
253
|
const fd = openSync(filePath, 'r');
|
|
254
254
|
const header = Buffer.alloc(12);
|
|
255
255
|
try {
|
package/dist/video/render.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import type { VideoRenderJob } from './types.js';
|
|
2
|
+
/** 내레이션 아래 배경음 크기 (약 -12 dB). 덕킹 대신 고정 게인 — 설계 문서 §9 Q4. */
|
|
3
|
+
export declare const MUSIC_UNDER_NARRATION = 0.25;
|
|
4
|
+
/**
|
|
5
|
+
* 짧은 FFmpeg 작업을 동기적으로(호출 안에서) 돌린다 — 내레이션 트랙 합치기처럼 수 초면 끝나는 일.
|
|
6
|
+
* 긴 렌더는 startRender 의 비동기 작업을 쓴다. 실행 파일은 렌더와 같은 규칙(MIMI_SEED_FFMPEG_PATH / PATH)으로 고른다.
|
|
7
|
+
*/
|
|
8
|
+
export declare function runFfmpeg(args: string[], cwd: string): Promise<void>;
|
|
2
9
|
declare function processAlive(pid: number | undefined): boolean;
|
|
3
10
|
declare function readTail(filePath: string, maxBytes?: number): string;
|
|
4
11
|
export interface FfmpegPlan {
|
package/dist/video/render.js
CHANGED
|
@@ -56,6 +56,29 @@ const M = catalog({
|
|
|
56
56
|
codec: (codec) => `Not the recommended codec H.264: ${codec}`,
|
|
57
57
|
pixFmt: (fmt) => `Not the recommended pixel format yuv420p: ${fmt}`,
|
|
58
58
|
});
|
|
59
|
+
/** 내레이션 아래 배경음 크기 (약 -12 dB). 덕킹 대신 고정 게인 — 설계 문서 §9 Q4. */
|
|
60
|
+
export const MUSIC_UNDER_NARRATION = 0.25;
|
|
61
|
+
/**
|
|
62
|
+
* 짧은 FFmpeg 작업을 동기적으로(호출 안에서) 돌린다 — 내레이션 트랙 합치기처럼 수 초면 끝나는 일.
|
|
63
|
+
* 긴 렌더는 startRender 의 비동기 작업을 쓴다. 실행 파일은 렌더와 같은 규칙(MIMI_SEED_FFMPEG_PATH / PATH)으로 고른다.
|
|
64
|
+
*/
|
|
65
|
+
export async function runFfmpeg(args, cwd) {
|
|
66
|
+
const ffmpeg = process.env.MIMI_SEED_FFMPEG_PATH ?? 'ffmpeg';
|
|
67
|
+
await verifyExecutable(ffmpeg);
|
|
68
|
+
try {
|
|
69
|
+
await execFileAsync(ffmpeg, ['-nostdin', '-y', ...args], {
|
|
70
|
+
cwd,
|
|
71
|
+
timeout: 120_000,
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
const raw = error.stderr;
|
|
78
|
+
const stderr = typeof raw === 'string' ? raw : raw?.toString('utf8') ?? '';
|
|
79
|
+
throw new Error(`${M().ffmpegExit(error.code ?? null)}\n${stderr.split(/\r?\n/).slice(-15).join('\n')}`, { cause: error });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
59
82
|
function jobPath(projectDir, jobId) {
|
|
60
83
|
return path.join(path.resolve(projectDir), '.jobs', `${jobId}.json`);
|
|
61
84
|
}
|
|
@@ -124,6 +147,16 @@ export function buildFfmpegPlan(projectDir, outputPath, jobId) {
|
|
|
124
147
|
audioIndex = assets.length;
|
|
125
148
|
args.push('-stream_loop', '-1', '-i', audio.path);
|
|
126
149
|
}
|
|
150
|
+
// 내레이션은 반복하지 않는다 — 배경음(audioAssetId)과 달리 한 번만 재생하고, 짧으면 무음으로 채운다.
|
|
151
|
+
let narrationIndex;
|
|
152
|
+
if (timeline.narrationAssetId) {
|
|
153
|
+
const narration = byId.get(timeline.narrationAssetId);
|
|
154
|
+
if (!narration || narration.kind !== 'audio' || !narration.allowedForRendering || !existsSync(narration.path)) {
|
|
155
|
+
throw new Error(M().audioAsset(timeline.narrationAssetId));
|
|
156
|
+
}
|
|
157
|
+
narrationIndex = assets.length + (audioIndex !== undefined ? 1 : 0);
|
|
158
|
+
args.push('-i', narration.path);
|
|
159
|
+
}
|
|
127
160
|
const filters = timeline.scenes.map((scene, index) => (`[${index}:v]scale=${project.settings.width}:${project.settings.height}:force_original_aspect_ratio=increase,` +
|
|
128
161
|
`crop=${project.settings.width}:${project.settings.height},fps=${project.settings.fps},` +
|
|
129
162
|
`trim=duration=${scene.durationSec},setpts=PTS-STARTPTS,format=yuv420p[v${index}]`));
|
|
@@ -140,10 +173,24 @@ export function buildFfmpegPlan(projectDir, outputPath, jobId) {
|
|
|
140
173
|
filters.push(`[base]subtitles=${relativeSubtitlePath}[vout]`);
|
|
141
174
|
videoLabel = '[vout]';
|
|
142
175
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
176
|
+
const total = timeline.totalDurationSec;
|
|
177
|
+
let audioMap = [];
|
|
178
|
+
if (narrationIndex !== undefined) {
|
|
179
|
+
// apad 로 무한히 늘린 뒤 atrim 으로 영상 길이에 정확히 맞춘다 — -shortest 가 영상을 자르지 않게.
|
|
180
|
+
filters.push(`[${narrationIndex}:a]apad,atrim=0:${total},asetpts=PTS-STARTPTS[nar]`);
|
|
181
|
+
if (audioIndex !== undefined) {
|
|
182
|
+
filters.push(`[${audioIndex}:a]volume=${MUSIC_UNDER_NARRATION},atrim=0:${total},asetpts=PTS-STARTPTS[bg]`);
|
|
183
|
+
filters.push('[nar][bg]amix=inputs=2:duration=first:normalize=0[aout]');
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
filters.push('[nar]anull[aout]');
|
|
187
|
+
}
|
|
188
|
+
audioMap = ['-map', '[aout]', '-c:a', 'aac', '-b:a', '192k'];
|
|
189
|
+
}
|
|
190
|
+
else if (audioIndex !== undefined) {
|
|
191
|
+
audioMap = ['-map', `${audioIndex}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-shortest'];
|
|
146
192
|
}
|
|
193
|
+
args.push('-filter_complex', filters.join(';'), '-map', videoLabel, ...audioMap);
|
|
147
194
|
args.push('-t', String(timeline.totalDurationSec), '-c:v', 'libx264', '-preset', 'medium', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', outputPath);
|
|
148
195
|
return { args, outputPath, subtitlePath };
|
|
149
196
|
}
|
package/dist/video/schemas.d.ts
CHANGED
|
@@ -146,6 +146,7 @@ export declare const timelineSchema: z.ZodObject<{
|
|
|
146
146
|
narration: z.ZodOptional<z.ZodString>;
|
|
147
147
|
}, z.core.$strip>>;
|
|
148
148
|
audioAssetId: z.ZodOptional<z.ZodString>;
|
|
149
|
+
narrationAssetId: z.ZodOptional<z.ZodString>;
|
|
149
150
|
captionStyle: z.ZodOptional<z.ZodObject<{
|
|
150
151
|
preset: z.ZodOptional<z.ZodEnum<{
|
|
151
152
|
shorts: "shorts";
|
package/dist/video/schemas.js
CHANGED
|
@@ -97,6 +97,7 @@ export const timelineSchema = z.object({
|
|
|
97
97
|
totalDurationSec: z.number().finite().positive().max(300),
|
|
98
98
|
scenes: z.array(timelineSceneSchema).min(1).max(30),
|
|
99
99
|
audioAssetId: z.string().min(1).max(200).optional(),
|
|
100
|
+
narrationAssetId: z.string().min(1).max(200).optional(),
|
|
100
101
|
captionStyle: captionStyleSchema.optional(),
|
|
101
102
|
}).superRefine((timeline, ctx) => {
|
|
102
103
|
const calculated = timeline.scenes.reduce((sum, scene) => sum + scene.durationSec, 0);
|
package/dist/video/types.d.ts
CHANGED
|
@@ -72,6 +72,8 @@ export interface VideoTimeline {
|
|
|
72
72
|
totalDurationSec: number;
|
|
73
73
|
scenes: VideoTimelineScene[];
|
|
74
74
|
audioAssetId?: string;
|
|
75
|
+
/** 한 번만 재생되는 내레이션 트랙. audioAssetId(배경음)와 함께 있으면 배경음을 줄여 섞는다. */
|
|
76
|
+
narrationAssetId?: string;
|
|
75
77
|
captionStyle?: VideoCaptionStyle;
|
|
76
78
|
}
|
|
77
79
|
export type VideoJobStatus = 'queued' | 'running' | 'completed' | 'failed';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Windows 음성 이름 (예: "Microsoft Heami Desktop"). 따옴표·세미콜론 같은 글자는 받지 않는다. */
|
|
2
|
+
export declare const WINDOWS_VOICE: RegExp;
|
|
3
|
+
export interface WindowsVoice {
|
|
4
|
+
voiceId: string;
|
|
5
|
+
name: string;
|
|
6
|
+
culture: string;
|
|
7
|
+
gender: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function listWindowsVoices(): Promise<WindowsVoice[]>;
|
|
10
|
+
/** WAV(RIFF) 머리에서 소리 길이(초)를 잰다. fmt 의 초당 바이트 수와 data 크기로 계산한다. */
|
|
11
|
+
export declare function wavSeconds(bytes: Buffer): number;
|
|
12
|
+
/**
|
|
13
|
+
* 문구 하나를 WAV 로 만든다. voice 를 주지 않으면 lang(예: ko) 에 맞는 첫 목소리. 맞는 목소리가 없으면 실패한다.
|
|
14
|
+
* 돌려주는 값: 실제로 쓴 목소리 이름과 음성 길이(초).
|
|
15
|
+
*/
|
|
16
|
+
export declare function speakToWav(text: string, outPath: string, options: {
|
|
17
|
+
voice?: string;
|
|
18
|
+
lang: string;
|
|
19
|
+
}): Promise<{
|
|
20
|
+
voice: string;
|
|
21
|
+
speechSec: number;
|
|
22
|
+
}>;
|