@yoonion/mimi-seed-mcp 0.31.0 → 0.32.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.
@@ -0,0 +1,270 @@
1
+ // ElevenLabs 내레이션 — 스토리보드 장면별 음성을 만들고, 장면 길이에 맞춰 한 트랙으로 합친다.
2
+ //
3
+ // 설계: docs/design/media-generation-providers.md §4.1.
4
+ // - 길이 기준은 스토리보드다. 음성이 장면보다 길면 늘이거나 자르지 않고 overruns 로 돌려준다.
5
+ // - 장면 음성은 (voiceId, modelId, text) 해시로 캐시한다. 이미 돈을 낸 장면은 다시 요청하지 않는다.
6
+ // - 키(ELEVENLABS_API_KEY)는 api.elevenlabs.io 에만 보낸다. 리디렉션은 따라가지 않는다.
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { z } from 'zod';
11
+ import { catalog } from '#core/lang.js';
12
+ import { fetchWithTimeout } from '../lib/http.js';
13
+ import { encodePathSegment } from '../lib/url-path.js';
14
+ import { readJson, writeJsonAtomic } from './files.js';
15
+ import { loadProject, registerAsset } from './project.js';
16
+ import { sanitizeExternalText } from './providers.js';
17
+ import { runFfmpeg } from './render.js';
18
+ const M = catalog({
19
+ envRequired: '❌ ELEVENLABS_API_KEY 환경변수가 필요합니다.',
20
+ apiFailed: (status, message) => `ElevenLabs 요청 실패 (${status}): ${message}`,
21
+ badResponse: 'ElevenLabs 응답 형식이 예상과 다릅니다.',
22
+ badAudio: 'ElevenLabs 응답이 유효한 20MB 이하 MP3가 아닙니다.',
23
+ noAlignment: 'ElevenLabs 응답에 음성 타이밍(alignment)이 없어 길이를 잴 수 없습니다.',
24
+ noNarration: '내레이션 문구가 있는 장면이 없습니다. video_save_plan 의 scenes[].narration 을 채우세요.',
25
+ license: 'ElevenLabs generated output; commercial use depends on the ElevenLabs plan and terms',
26
+ next: 'video_build_timeline 에 narrationAssetId 로 넘기세요. 타임라인 장면 길이는 프로젝트 장면 길이와 같게 두세요.',
27
+ }, {
28
+ envRequired: '❌ The ELEVENLABS_API_KEY environment variable is required.',
29
+ apiFailed: (status, message) => `ElevenLabs request failed (${status}): ${message}`,
30
+ badResponse: 'The ElevenLabs response has an unexpected shape.',
31
+ badAudio: 'The ElevenLabs response is not a valid MP3 of 20MB or less.',
32
+ noAlignment: 'The ElevenLabs response has no timing (alignment), so its length cannot be measured.',
33
+ noNarration: 'No scene has narration text. Fill scenes[].narration with video_save_plan.',
34
+ license: 'ElevenLabs generated output; commercial use depends on the ElevenLabs plan and terms',
35
+ next: 'Pass it to video_build_timeline as narrationAssetId. Keep the timeline scene durations equal to the project scenes.',
36
+ });
37
+ const API = 'https://api.elevenlabs.io';
38
+ export const DEFAULT_TTS_MODEL = 'eleven_multilingual_v2';
39
+ const OUTPUT_FORMAT = 'mp3_44100_128';
40
+ const MAX_AUDIO_BYTES = 20 * 1024 * 1024;
41
+ /** 음성이 장면보다 이만큼까지 길어도 허용한다 — 문장 끝 숨소리 정도. */
42
+ const OVERRUN_TOLERANCE_SEC = 0.05;
43
+ export const VOICE_ID = /^[A-Za-z0-9]{1,64}$/;
44
+ export const TTS_MODEL_ID = /^[a-z0-9_]{1,64}$/;
45
+ function apiKey() {
46
+ const value = process.env.ELEVENLABS_API_KEY?.trim();
47
+ if (!value)
48
+ throw new Error(M().envRequired);
49
+ return value;
50
+ }
51
+ async function callElevenLabs(url, init) {
52
+ const response = await fetchWithTimeout(url, {
53
+ ...init,
54
+ // 키를 다른 호스트로 들고 가지 않게 리디렉션은 실패로 본다.
55
+ redirect: 'error',
56
+ headers: { 'xi-api-key': apiKey(), Accept: 'application/json', ...(init.headers ?? {}) },
57
+ });
58
+ const text = await response.text();
59
+ if (!response.ok) {
60
+ throw new Error(M().apiFailed(response.status, sanitizeExternalText(text, 500)));
61
+ }
62
+ try {
63
+ return JSON.parse(text);
64
+ }
65
+ catch (error) {
66
+ throw new Error(M().badResponse, { cause: error });
67
+ }
68
+ }
69
+ // ── voices ────────────────────────────────────────────────────────────────
70
+ const voicesResponse = z.object({
71
+ voices: z.array(z.object({
72
+ voice_id: z.string(),
73
+ name: z.string().nullish(),
74
+ category: z.string().nullish(),
75
+ labels: z.record(z.string(), z.string()).nullish(),
76
+ description: z.string().nullish(),
77
+ preview_url: z.string().nullish(),
78
+ })),
79
+ has_more: z.boolean().optional(),
80
+ next_page_token: z.string().nullish(),
81
+ });
82
+ export async function listVoices(input) {
83
+ const params = new URLSearchParams({ page_size: String(input.pageSize ?? 30) });
84
+ if (input.search)
85
+ params.set('search', input.search);
86
+ if (input.nextPageToken)
87
+ params.set('next_page_token', input.nextPageToken);
88
+ const parsed = voicesResponse.safeParse(await callElevenLabs(`${API}/v2/voices?${params}`, { method: 'GET' }));
89
+ if (!parsed.success)
90
+ throw new Error(M().badResponse);
91
+ return {
92
+ voices: parsed.data.voices.map((voice) => ({
93
+ voiceId: voice.voice_id,
94
+ name: sanitizeExternalText(voice.name ?? '', 200),
95
+ category: voice.category ?? undefined,
96
+ labels: Object.fromEntries(Object.entries(voice.labels ?? {})
97
+ .slice(0, 20)
98
+ .map(([key, value]) => [sanitizeExternalText(key, 50), sanitizeExternalText(value, 100)])),
99
+ description: voice.description ? sanitizeExternalText(voice.description, 500) : undefined,
100
+ previewUrl: voice.preview_url ?? undefined,
101
+ })),
102
+ hasMore: parsed.data.has_more ?? false,
103
+ nextPageToken: parsed.data.next_page_token ?? undefined,
104
+ untrustedExternalText: true,
105
+ };
106
+ }
107
+ const cacheMeta = z.object({ speechSec: z.number().finite().nonnegative() });
108
+ function cacheDir(projectDir) {
109
+ return path.join(path.resolve(projectDir), 'assets', 'generated', 'narration-cache');
110
+ }
111
+ /**
112
+ * 네트워크 없이 계획만 세운다 — 미리보기와 실행이 같은 장면 선택·캐시 판단을 쓰게.
113
+ * 과금 근거는 캐시되지 않은 장면의 글자 수다 (ElevenLabs 는 글자 수로 과금한다).
114
+ */
115
+ export function planNarration(input) {
116
+ const project = loadProject(input.projectDir);
117
+ const modelId = input.modelId ?? DEFAULT_TTS_MODEL;
118
+ const segments = [];
119
+ for (const scene of project.scenes) {
120
+ const text = scene.narration.trim();
121
+ if (!text)
122
+ continue;
123
+ const hash = createHash('sha256').update(JSON.stringify([input.voiceId, modelId, text])).digest('hex');
124
+ const audioPath = path.join(cacheDir(input.projectDir), `${hash}.mp3`);
125
+ const metaPath = path.join(cacheDir(input.projectDir), `${hash}.json`);
126
+ segments.push({
127
+ sceneId: scene.id,
128
+ sceneSec: scene.durationSec,
129
+ text,
130
+ characters: [...text].length,
131
+ cached: existsSync(audioPath) && existsSync(metaPath),
132
+ audioPath,
133
+ metaPath,
134
+ });
135
+ }
136
+ if (segments.length === 0)
137
+ throw new Error(M().noNarration);
138
+ return {
139
+ voiceId: input.voiceId,
140
+ modelId,
141
+ segments,
142
+ billableCharacters: segments.filter((s) => !s.cached).reduce((sum, s) => sum + s.characters, 0),
143
+ cachedScenes: segments.filter((s) => s.cached).length,
144
+ };
145
+ }
146
+ const timestampsResponse = z.object({
147
+ audio_base64: z.string().min(1),
148
+ alignment: z.object({ character_end_times_seconds: z.array(z.number()) }).nullish(),
149
+ normalized_alignment: z.object({ character_end_times_seconds: z.array(z.number()) }).nullish(),
150
+ });
151
+ /** MP3 = ID3 태그 또는 MPEG 프레임 동기 (0xFFE). */
152
+ export function hasMp3Signature(bytes) {
153
+ if (bytes.length < 3)
154
+ return false;
155
+ if (bytes.subarray(0, 3).toString('ascii') === 'ID3')
156
+ return true;
157
+ return bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0;
158
+ }
159
+ /** 응답에서 음성 길이(마지막 글자의 끝 시각)를 뽑는다. */
160
+ export function speechSecondsFrom(body) {
161
+ const parsed = timestampsResponse.safeParse(body);
162
+ if (!parsed.success)
163
+ throw new Error(M().badResponse);
164
+ const bytes = Buffer.from(parsed.data.audio_base64, 'base64');
165
+ if (bytes.length === 0 || bytes.length > MAX_AUDIO_BYTES || !hasMp3Signature(bytes))
166
+ throw new Error(M().badAudio);
167
+ const ends = parsed.data.alignment?.character_end_times_seconds
168
+ ?? parsed.data.normalized_alignment?.character_end_times_seconds;
169
+ if (!ends?.length)
170
+ throw new Error(M().noAlignment);
171
+ return { bytes, speechSec: Math.max(...ends) };
172
+ }
173
+ function writeFileAtomic(destination, bytes) {
174
+ const temp = `${destination}.${randomUUID()}.tmp`;
175
+ try {
176
+ writeFileSync(temp, bytes, { flag: 'wx' });
177
+ renameSync(temp, destination);
178
+ }
179
+ catch (error) {
180
+ try {
181
+ unlinkSync(temp);
182
+ }
183
+ catch {
184
+ // 임시 파일이 만들어지기 전에 실패했을 수 있다 — 원래 오류를 그대로 던진다.
185
+ }
186
+ throw error;
187
+ }
188
+ }
189
+ async function synthesize(segment, voiceId, modelId) {
190
+ const url = `${API}/v1/text-to-speech/${encodePathSegment(voiceId)}/with-timestamps?output_format=${OUTPUT_FORMAT}`;
191
+ const body = await callElevenLabs(url, {
192
+ method: 'POST',
193
+ headers: { 'Content-Type': 'application/json' },
194
+ body: JSON.stringify({ text: segment.text, model_id: modelId }),
195
+ });
196
+ const { bytes, speechSec } = speechSecondsFrom(body);
197
+ mkdirSync(path.dirname(segment.audioPath), { recursive: true });
198
+ writeFileAtomic(segment.audioPath, bytes);
199
+ // 메타는 오디오 다음에 쓴다 — 둘 다 있어야 캐시로 인정되므로, 중간에 죽으면 다음 호출이 다시 만든다.
200
+ writeJsonAtomic(segment.metaPath, { speechSec });
201
+ return speechSec;
202
+ }
203
+ /**
204
+ * 장면별 음성을 장면 길이만큼 무음으로 채워 이어 붙이는 FFmpeg 인자.
205
+ * 내레이션이 없는 장면은 anullsrc 무음으로 자리를 채운다.
206
+ */
207
+ export function buildNarrationMixArgs(scenes, outputPath) {
208
+ const inputs = [];
209
+ const filters = [];
210
+ let inputIndex = 0;
211
+ scenes.forEach((scene, index) => {
212
+ if (scene.audioPath) {
213
+ inputs.push('-i', scene.audioPath);
214
+ filters.push(`[${inputIndex}:a]aformat=sample_rates=44100:channel_layouts=stereo,apad,` +
215
+ `atrim=0:${scene.sceneSec},asetpts=PTS-STARTPTS[s${index}]`);
216
+ inputIndex += 1;
217
+ }
218
+ else {
219
+ filters.push(`anullsrc=r=44100:cl=stereo,atrim=0:${scene.sceneSec},asetpts=PTS-STARTPTS[s${index}]`);
220
+ }
221
+ });
222
+ filters.push(`${scenes.map((_, index) => `[s${index}]`).join('')}concat=n=${scenes.length}:v=0:a=1[out]`);
223
+ return [...inputs, '-filter_complex', filters.join(';'), '-map', '[out]', '-c:a', 'aac', '-b:a', '192k', outputPath];
224
+ }
225
+ export async function generateNarration(input) {
226
+ const plan = planNarration(input);
227
+ const project = loadProject(input.projectDir);
228
+ const speech = new Map();
229
+ const results = [];
230
+ for (const segment of plan.segments) {
231
+ const speechSec = segment.cached
232
+ ? cacheMeta.parse(readJson(segment.metaPath)).speechSec
233
+ : await synthesize(segment, plan.voiceId, plan.modelId);
234
+ speech.set(segment.sceneId, speechSec);
235
+ results.push({ sceneId: segment.sceneId, speechSec, sceneSec: segment.sceneSec, cached: segment.cached });
236
+ }
237
+ const overruns = results.filter((r) => r.speechSec > r.sceneSec + OVERRUN_TOLERANCE_SEC);
238
+ if (overruns.length) {
239
+ // 스토리보드가 기준이다 — 자르거나 늘리지 않고 에이전트가 문구나 장면 길이를 고치게 한다.
240
+ return { registered: false, overruns, segments: results };
241
+ }
242
+ const bySceneId = new Map(plan.segments.map((s) => [s.sceneId, s]));
243
+ const id = `narration-${randomUUID()}`;
244
+ const outputPath = path.join(path.resolve(input.projectDir), 'assets', 'generated', `${id}.m4a`);
245
+ mkdirSync(path.dirname(outputPath), { recursive: true });
246
+ // 내레이션이 없는 장면도 자리를 무음으로 채워야 트랙 전체가 영상 장면 경계와 맞는다.
247
+ const args = buildNarrationMixArgs(project.scenes.map((scene) => ({
248
+ sceneSec: scene.durationSec,
249
+ audioPath: speech.has(scene.id) ? bySceneId.get(scene.id)?.audioPath : undefined,
250
+ })), outputPath);
251
+ await runFfmpeg(args, path.resolve(input.projectDir));
252
+ const asset = registerAsset(input.projectDir, {
253
+ id,
254
+ kind: 'audio',
255
+ sourceType: 'generated',
256
+ path: outputPath,
257
+ license: M().license,
258
+ attribution: `ElevenLabs voice ${plan.voiceId}`,
259
+ allowedForRendering: true,
260
+ provider: `elevenlabs:${plan.modelId}`,
261
+ prompt: plan.segments.map((s) => `[${s.sceneId}] ${s.text}`).join('\n'),
262
+ });
263
+ return {
264
+ registered: true,
265
+ asset,
266
+ totalDurationSec: project.scenes.reduce((sum, scene) => sum + scene.durationSec, 0),
267
+ segments: results,
268
+ next: M().next,
269
+ };
270
+ }
@@ -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;
@@ -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
- if (audioAssetId) {
302
- const audio = byId.get(audioAssetId);
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(audioAssetId));
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 hasMp4Signature(filePath: string): boolean;
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;
@@ -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 {
@@ -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 {
@@ -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
- args.push('-filter_complex', filters.join(';'), '-map', videoLabel);
144
- if (audioIndex !== undefined) {
145
- args.push('-map', `${audioIndex}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-shortest');
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
  }
@@ -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";
@@ -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);
@@ -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';
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@yoonion/mimi-seed-mcp",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@yoonion/mimi-seed-mcp",
9
- "version": "0.31.0",
9
+ "version": "0.32.0",
10
10
  "license": "PolyForm-Noncommercial-1.0.0",
11
11
  "dependencies": {
12
12
  "@googleapis/admob": "^11.0.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yoonion/mimi-seed-mcp",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "Mimi Seed MCP server — Firebase + AdMob + Google Play + App Store management for Claude Code / Codex / Cursor / any MCP client.",
5
5
  "type": "module",
6
6
  "imports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$comment": "등록된 MCP 도구 + 도메인 메타데이터(label·credential·summary) + 도구 분류(write·destructive·local·idempotent → MCP annotations·confirm 가드) + toolset 그룹·폐기 별칭의 SSOT (src/lib/tool-registrar.ts 가 읽는다). src/__tests__/tool-manifest.test.ts 가 실제 서버 등록 목록과 diff 하고 메타데이터 정합성을 검사한다. 도구 추가/삭제/개명 시 이 파일을 함께 갱신할 것 — 산문 문서에는 정확한 개수를 쓰지 말고 이 파일을 가리킬 것. mimi-seed://tools/catalog 리소스가 이 파일을 그대로 서빙한다.",
3
- "total": 281,
3
+ "total": 285,
4
4
  "alwaysOn": [
5
5
  "auth",
6
6
  "checks",
@@ -903,7 +903,11 @@
903
903
  "video_build_timeline",
904
904
  "video_render",
905
905
  "video_job_status",
906
- "video_validate"
906
+ "video_validate",
907
+ "video_list_voices",
908
+ "video_generate_narration",
909
+ "video_generate_clip",
910
+ "video_clip_status"
907
911
  ],
908
912
  "write": [
909
913
  "video_plan_from_story",
@@ -917,7 +921,10 @@
917
921
  "video_build_timeline",
918
922
  "video_render",
919
923
  "youtube_upload_video",
920
- "youtube_update_video_privacy"
924
+ "youtube_update_video_privacy",
925
+ "video_generate_narration",
926
+ "video_generate_clip",
927
+ "video_clip_status"
921
928
  ],
922
929
  "destructive": [],
923
930
  "ownGate": [],
@@ -931,7 +938,8 @@
931
938
  ],
932
939
  "idempotent": [
933
940
  "video_build_timeline",
934
- "youtube_update_video_privacy"
941
+ "youtube_update_video_privacy",
942
+ "video_clip_status"
935
943
  ]
936
944
  },
937
945
  "youtube": {