Spaces:
Sleeping

File size: 19,930 Bytes
9713441
 
 
 
 
8d2c959
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
8d2c959
9713441
 
8d2c959
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d2c959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
8d2c959
9713441
 
8d2c959
9713441
8d2c959
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d2c959
9713441
 
 
 
 
 
8d2c959
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d2c959
9713441
 
 
 
8d2c959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
8d2c959
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d2c959
9713441
 
 
 
 
8d2c959
 
 
 
 
 
9713441
 
 
 
 
 
 
8d2c959
 
 
 
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { db, AUDIO_CACHE_DIR, logUsage } from '../db/database.js';
import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js';
import { probeMediaDurationSec } from './assetAnalysisService.js';
import type { WordTimestamp } from '@olokaflow/shared';

const execFileAsync = promisify(execFile);

export interface VoiceCatalogItem {
  id: string;
  name: string;
  voiceId: string;
  gender: string;
  region: string;
  description: string;
  lang: string;
  provider: 'olokatts' | 'openai' | 'cloned';
  isEditorsPick?: boolean;
  previewUrl?: string;
  refText?: string;
  sampleAudioPath?: string;
  fallbackVoiceId?: string;
}

export interface SynthesizedSceneVoice {
  audioUrl: string;
  audioDurationSec: number;
  sceneDurationSec: number;
  words: WordTimestamp[];
  fromCache: boolean;
}

const OLOKATTS_BASE_URL = 'https://tts.oloka.net';

export const STATIC_FALLBACK_VOICES: VoiceCatalogItem[] = [
  {
    id: 'vp_haidang',
    name: 'Hải Đăng (Nam • Miền Nam)',
    voiceId: 'Hải Đăng',
    gender: 'Nam',
    region: 'Nam',
    description: 'Trẻ trung, hiện đại, phong cách tự nhiên (Mặc định)',
    lang: 'Tiếng Việt',
    provider: 'olokatts',
    isEditorsPick: true,
    previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_haidang.wav`,
  },
  {
    id: 'vp_trucly',
    name: 'Trúc Ly (Nữ • Miền Bắc)',
    voiceId: 'Trúc Ly',
    gender: 'Nữ',
    region: 'Bắc',
    description: 'Trong trẻo, lôi cuốn, phong cách tự nhiên',
    lang: 'Tiếng Việt',
    provider: 'olokatts',
    isEditorsPick: true,
    previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_trucly.wav`,
  },
  {
    id: 'vp_anhkhoi',
    name: 'Anh Khôi (Nam • Miền Bắc)',
    voiceId: 'Anh Khôi',
    gender: 'Nam',
    region: 'Bắc',
    description: 'Trầm ấm, truyền cảm, phong cách kể chuyện',
    lang: 'Tiếng Việt',
    provider: 'olokatts',
    isEditorsPick: true,
    previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_anhkhoi.wav`,
  },
  {
    id: 'vp_maianh',
    name: 'Mai Anh (Nữ • Miền Bắc)',
    voiceId: 'Mai Anh',
    gender: 'Nữ',
    region: 'Bắc',
    description: 'Dịu dàng, chuẩn phát thanh, phong cách tin tức',
    lang: 'Tiếng Việt',
    provider: 'olokatts',
    isEditorsPick: true,
    previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_maianh.wav`,
  },
  {
    id: 'vp_adambua',
    name: 'Adam Bựa (Nam • Hài hước)',
    voiceId: 'Adam bựa',
    gender: 'Nam',
    region: 'Bắc',
    description: 'Hài hước, dí dỏm, độc đáo cho TikTok/Reels',
    lang: 'Tiếng Việt',
    provider: 'olokatts',
    isEditorsPick: true,
    previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_adambua.wav`,
  },
  {
    id: 'nova',
    name: 'Nova (OpenAI • Nữ năng lượng)',
    voiceId: 'nova',
    gender: 'Nữ',
    region: 'Quốc tế / Đa ngôn ngữ',
    description: 'Giọng nữ hiện đại, giàu năng lượng chuẩn OpenAI',
    lang: 'Multi / VI',
    provider: 'openai',
  },
  {
    id: 'alloy',
    name: 'Alloy (OpenAI • Trung tính)',
    voiceId: 'alloy',
    gender: 'Trung tính',
    region: 'Quốc tế / Đa ngôn ngữ',
    description: 'Giọng thuyết minh cân bằng, chuyên nghiệp',
    lang: 'Multi / VI',
    provider: 'openai',
  },
  {
    id: 'onyx',
    name: 'Onyx (OpenAI • Nam trầm ấm)',
    voiceId: 'onyx',
    gender: 'Nam',
    region: 'Quốc tế / Đa ngôn ngữ',
    description: 'Giọng nam sâu, uy tín cho giới thiệu doanh nghiệp',
    lang: 'Multi / VI',
    provider: 'openai',
  },
  {
    id: 'shimmer',
    name: 'Shimmer (OpenAI • Nữ dịu dàng)',
    voiceId: 'shimmer',
    gender: 'Nữ',
    region: 'Quốc tế / Đa ngôn ngữ',
    description: 'Giọng nữ nhẹ nhàng cho lifestyle & kể chuyện',
    lang: 'Multi / VI',
    provider: 'openai',
  },
];

let cachedLiveVoices: VoiceCatalogItem[] | null = null;
let cachedVoicesTimestamp = 0;

export function listCustomClonedVoices(): VoiceCatalogItem[] {
  try {
    const rows = db
      .prepare('SELECT * FROM custom_voices ORDER BY created_at DESC')
      .all() as any[];
    return rows.map((r) => ({
      id: r.id,
      name: `${r.name} (Clone • ${r.gender})`,
      voiceId: r.voice_id || r.id,
      gender: r.gender || 'Nam',
      region: r.region || 'Việt Nam',
      description:
        r.description || 'Giọng đọc Clone cá nhân hóa (Zero-Shot Voice Clone)',
      lang: 'Tiếng Việt',
      provider: 'cloned' as const,
      isEditorsPick: true,
      previewUrl: r.sample_public_url || '',
      refText: r.ref_text || '',
      sampleAudioPath: r.sample_audio_path || '',
      fallbackVoiceId: r.fallback_voice_id || 'Hải Đăng',
    }));
  } catch {
    return [];
  }
}

export function createCustomClonedVoice(params: {
  name: string;
  gender: string;
  region: string;
  description?: string;
  refText?: string;
  sampleAudioPath: string;
  samplePublicUrl: string;
  fallbackVoiceId?: string;
}): VoiceCatalogItem {
  const id = `vc-clone-${crypto.randomUUID().slice(0, 8)}`;
  const now = new Date().toISOString();
  const cleanName = params.name.trim() || 'Giọng Clone Mới';
  const fallbackVoice =
    params.fallbackVoiceId || (params.gender === 'Nữ' ? 'Trúc Ly' : 'Hải Đăng');

  db.prepare(`
    INSERT INTO custom_voices (
      id, name, voice_id, gender, region, description, ref_text,
      sample_audio_path, sample_public_url, fallback_voice_id, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    id,
    cleanName,
    id,
    params.gender || 'Nam',
    params.region || 'Việt Nam',
    params.description || 'Giọng đọc Clone cá nhân hóa từ file mẫu',
    params.refText || '',
    params.sampleAudioPath,
    params.samplePublicUrl,
    fallbackVoice,
    now
  );

  cachedLiveVoices = null;
  return listCustomClonedVoices().find((v) => v.id === id)!;
}

export function deleteCustomClonedVoice(id: string): void {
  db.prepare('DELETE FROM custom_voices WHERE id = ?').run(id);
  cachedLiveVoices = null;
}

/**
 * Fetches the live 25 Vietnamese voices from https://tts.oloka.net/v1/voices
 * and merges with custom cloned voices + OpenAI standard voices.
 */
export async function listAvailableVoices(): Promise<VoiceCatalogItem[]> {
  const customClones = listCustomClonedVoices();
  if (cachedLiveVoices && Date.now() - cachedVoicesTimestamp < 5 * 60 * 1000) {
    return [...customClones, ...cachedLiveVoices];
  }

  try {
    const resp = await fetch(`${OLOKATTS_BASE_URL}/v1/voices`, {
      signal: AbortSignal.timeout(8000),
    });
    if (resp.ok) {
      const payload = (await resp.json()) as any[];
      if (Array.isArray(payload) && payload.length > 0) {
        const olokaVoices: VoiceCatalogItem[] = payload
          .map((row) => {
            const voiceId = String(row.voice_id || row.name || '').trim();
            if (!voiceId) return null;
            const preview = String(row.preview_audio_url || '');
            const previewUrl = preview.startsWith('/')
              ? `${OLOKATTS_BASE_URL}${preview}`
              : preview.startsWith('http')
                ? preview
                : '';
            const gender = String(row.gender || 'Nam');
            const region = String(row.region || 'Việt Nam');
            return {
              id: String(row.id || voiceId),
              name: `${row.name || voiceId} (${gender} • Miền ${region})`,
              voiceId,
              gender,
              region,
              description: String(row.description || 'Giọng đọc AI tiếng Việt tự nhiên').slice(0, 160),
              lang: 'Tiếng Việt',
              provider: 'olokatts' as const,
              isEditorsPick: Boolean(row.is_editors_pick),
              previewUrl,
            };
          })
          .filter(Boolean) as VoiceCatalogItem[];

        const openaiExtras = STATIC_FALLBACK_VOICES.filter((v) => v.provider === 'openai');
        cachedLiveVoices = [...olokaVoices, ...openaiExtras];
        cachedVoicesTimestamp = Date.now();
        return [...customClones, ...cachedLiveVoices];
      }
    }
  } catch (err: any) {
    console.warn(`[VoiceService] Live OlokaTTS catalog fetch note: ${err.message}`);
  }

  return [...customClones, ...STATIC_FALLBACK_VOICES];
}

export const AVAILABLE_VOICES = STATIC_FALLBACK_VOICES;

const VI_DIGITS = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'];

function readTwoDigitsVi(n: number): string {
  if (n < 10) return VI_DIGITS[n];
  const tens = Math.floor(n / 10);
  const ones = n % 10;
  const tensText = tens === 1 ? 'mười' : `${VI_DIGITS[tens]} mươi`;
  if (ones === 0) return tensText;
  if (ones === 1 && tens > 1) return `${tensText} mốt`;
  if (ones === 5) return `${tensText} lăm`;
  return `${tensText} ${VI_DIGITS[ones]}`;
}

function numberToViWords(numStr: string): string {
  const n = Number.parseInt(numStr, 10);
  if (!Number.isFinite(n) || n < 0 || n > 9999) return numStr;
  if (n < 100) return readTwoDigitsVi(n);
  if (n < 1000) {
    const hundreds = Math.floor(n / 100);
    const rem = n % 100;
    if (rem === 0) return `${VI_DIGITS[hundreds]} trăm`;
    if (rem < 10) return `${VI_DIGITS[hundreds]} trăm lẻ ${VI_DIGITS[rem]}`;
    return `${VI_DIGITS[hundreds]} trăm ${readTwoDigitsVi(rem)}`;
  }
  return numStr;
}

/**
 * Normalizes Vietnamese narration text for clean TTS pronunciation:
 * - Strips markdown/stage directions in brackets
 * - Expands percentages & small integers for natural Vietnamese TTS reading
 */
export function normalizeVietnameseTtsText(rawText: string): string {
  return (rawText || '')
    .replace(/\[(?:scene|cảnh|visual|sfx|bgm)[^\]]*\]/gi, ' ')
    .replace(/(\d+)\s*%/g, (_, d) => `${numberToViWords(d)} phần trăm`)
    .replace(/\s+/g, ' ')
    .trim();
}

/**
 * Generates proportional word-level timestamps weighted by character/syllable length
 * when ASR endpoint is not configured or as a fast deterministic sync rail.
 */
export function buildSyllableWeightedWordTimestamps(
  text: string,
  audioDurationSec: number
): WordTimestamp[] {
  const cleanTokens = (text || '')
    .replace(/\s+/g, ' ')
    .trim()
    .split(' ')
    .filter(Boolean);

  if (cleanTokens.length === 0) return [];

  const usableDuration = Math.max(1.2, audioDurationSec - 0.15);
  const weights = cleanTokens.map((w) => {
    const base = Math.max(2, w.length);
    const pauseBonus = /[.,;!?]$/.test(w) ? 2.2 : 0;
    return base + pauseBonus;
  });
  const totalWeight = weights.reduce((a, b) => a + b, 0) || 1;

  let cursor = 0.08;
  return cleanTokens.map((word, idx) => {
    const span = (weights[idx] / totalWeight) * usableDuration;
    const start = Number(cursor.toFixed(3));
    const end = Number(Math.min(audioDurationSec, cursor + span).toFixed(3));
    cursor += span;
    return { word, start, end };
  });
}

async function masterVoiceAudioToMp3(inputPath: string, outputMp3Path: string): Promise<boolean> {
  const isWin = process.platform === 'win32';
  const ffmpegCmd = isWin ? 'ffmpeg.exe' : 'ffmpeg';
  try {
    await execFileAsync(
      ffmpegCmd,
      [
        '-y',
        '-i',
        inputPath,
        '-af',
        'highpass=f=90,equalizer=f=3200:t=q:w=1.2:g=2.0,acompressor=threshold=-18dB:ratio=2.5:attack=15:release=180,loudnorm=I=-12.5:TP=-1.5:LRA=5',
        '-ar',
        '44100',
        '-ac',
        '1',
        '-c:a',
        'libmp3lame',
        '-b:a',
        '192k',
        outputMp3Path,
      ],
      { timeout: 25000 }
    );
    return fs.existsSync(outputMp3Path) && fs.statSync(outputMp3Path).size > 256;
  } catch {
    return false;
  }
}

export async function synthesizeSceneVoice(params: {
  projectId: string;
  sceneIndex: number;
  text: string;
  voiceId: string;
  speed?: number;
}): Promise<SynthesizedSceneVoice> {
  const cleanText = normalizeVietnameseTtsText(params.text || '');
  const speed = Math.max(0.5, Math.min(2.0, Number(params.speed || 1.0)));

  // Resolve voiceId against live catalog if an id like 'vp_haidang' or a cloned voice was passed
  const catalog = await listAvailableVoices();
  const matchedVoice = catalog.find(
    (v) => v.id === params.voiceId || v.voiceId === params.voiceId
  );
  const isClonedVoice = matchedVoice?.provider === 'cloned';
  const resolvedVoiceName = isClonedVoice
    ? matchedVoice.fallbackVoiceId || 'Hải Đăng'
    : matchedVoice
      ? matchedVoice.voiceId
      : params.voiceId || 'Hải Đăng';

  let clonedAudioB64 = '';
  if (
    isClonedVoice &&
    matchedVoice?.sampleAudioPath &&
    fs.existsSync(matchedVoice.sampleAudioPath)
  ) {
    try {
      clonedAudioB64 = fs
        .readFileSync(matchedVoice.sampleAudioPath)
        .toString('base64');
    } catch {}
  }

  const hash = crypto
    .createHash('sha256')
    .update(`${matchedVoice?.id || resolvedVoiceName}:${speed}:${cleanText}`)
    .digest('hex')
    .slice(0, 16);

  const mp3FileName = `vo-${hash}.mp3`;
  const wordsFileName = `vo-${hash}.words.json`;
  const mp3Path = path.join(AUDIO_CACHE_DIR, mp3FileName);
  const wordsPath = path.join(AUDIO_CACHE_DIR, wordsFileName);

  // 1. Check SHA-256 Scene TTS Cache first!
  if (fs.existsSync(mp3Path) && fs.existsSync(wordsPath)) {
    try {
      const cached = JSON.parse(fs.readFileSync(wordsPath, 'utf8'));
      return {
        audioUrl: `/media/audio_cache/${mp3FileName}`,
        audioDurationSec: cached.audioDurationSec,
        sceneDurationSec: cached.sceneDurationSec,
        words: cached.words,
        fromCache: true,
      };
    } catch {}
  }

  // Estimate speaking duration from Vietnamese word count (~2.9 words/sec at 1.0x)
  const wordCount = cleanText.split(/\s+/).filter(Boolean).length;
  const estimatedAudioDurationSec = Number(
    Math.max(2.6, wordCount / (2.9 * speed)).toFixed(2)
  );

  // 2. Try calling configured OpenAI-compatible / OlokaTTS endpoint
  const ttsTargets = resolveTargetsForRole('voice_tts');
  for (const target of ttsTargets) {
    const { profile, modelId } = target;
    if (!profile.baseUrl || !profile.apiKey) continue;

    const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol);
    const isOlokaTts = baseUrl.includes('tts.oloka.net');
    const speechEndpoint = baseUrl.endsWith('/v1')
      ? `${baseUrl}/audio/speech`
      : baseUrl.includes('tts.oloka.net')
        ? `${baseUrl}/v1/audio/speech`
        : `${baseUrl}/audio/speech`;

    const startTime = Date.now();
    try {
      const requestBody: Record<string, any> = isOlokaTts
        ? {
            model: modelId || 'olokatts-v3-turbo',
            voice: resolvedVoiceName,
            input: cleanText,
            speed,
            ...(clonedAudioB64
              ? {
                  reference_audio_b64: clonedAudioB64,
                  ref_text: matchedVoice?.refText || undefined,
                }
              : {}),
          }
        : {
            model: modelId || 'tts-1-hd',
            voice: resolvedVoiceName,
            input: cleanText,
            speed,
            response_format: 'mp3',
            ...(clonedAudioB64
              ? {
                  reference_audio_b64: clonedAudioB64,
                  ref_text: matchedVoice?.refText || undefined,
                }
              : {}),
          };

      const resp = await fetch(speechEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${profile.apiKey}`,
          ...(isOlokaTts ? { Accept: 'audio/wav' } : {}),
          ...profile.customHeaders,
        },
        body: JSON.stringify(requestBody),
        signal: AbortSignal.timeout(profile.timeoutMs || 120000),
      });

      if (!resp.ok) {
        const errBody = await resp.text().catch(() => '');
        throw new Error(`TTS HTTP ${resp.status}: ${errBody.slice(0, 160)}`);
      }

      const audioBuffer = Buffer.from(await resp.arrayBuffer());
      const rawTempPath = path.join(AUDIO_CACHE_DIR, `raw-${hash}.bin`);
      fs.writeFileSync(rawTempPath, audioBuffer);

      // Master audio to -12.5 LUFS MP3 if FFmpeg is installed, else save directly
      const mastered = await masterVoiceAudioToMp3(rawTempPath, mp3Path);
      if (!mastered) {
        fs.copyFileSync(rawTempPath, mp3Path);
      }
      try {
        fs.unlinkSync(rawTempPath);
      } catch {}

      const measuredDuration = await probeMediaDurationSec(
        mp3Path,
        estimatedAudioDurationSec
      );
      const sceneDurationSec = Number(
        Math.max(3.2, Math.ceil((measuredDuration + 0.45) * 10) / 10).toFixed(2)
      );

      // Try Whisper word-level ASR if configured
      let words = await tryTranscribeWordTimestamps(mp3Path, measuredDuration);
      if (!words || words.length === 0) {
        words = buildSyllableWeightedWordTimestamps(params.text || cleanText, measuredDuration);
      }

      fs.writeFileSync(
        wordsPath,
        JSON.stringify({ audioDurationSec: measuredDuration, sceneDurationSec, words }, null, 2),
        'utf8'
      );

      logUsage({
        projectId: params.projectId,
        profileId: profile.id,
        modelId: requestBody.model,
        role: 'voice_tts',
        ttsChars: cleanText.length,
        durationMs: Date.now() - startTime,
      });

      return {
        audioUrl: `/media/audio_cache/${mp3FileName}`,
        audioDurationSec: measuredDuration,
        sceneDurationSec,
        words,
        fromCache: false,
      };
    } catch (err: any) {
      console.warn(`[VoiceService] TTS profile "${profile.name}" failed: ${err.message}`);
    }
  }

  // 3. Fallback when TTS API key is not yet entered: compute accurate word timing rail
  const sceneDurationSec = Number(
    Math.max(3.5, Math.ceil((estimatedAudioDurationSec + 0.45) * 10) / 10).toFixed(2)
  );
  const words = buildSyllableWeightedWordTimestamps(
    params.text || cleanText,
    estimatedAudioDurationSec
  );

  return {
    audioUrl: '',
    audioDurationSec: estimatedAudioDurationSec,
    sceneDurationSec,
    words,
    fromCache: false,
  };
}

async function tryTranscribeWordTimestamps(
  mp3Path: string,
  fallbackDurationSec: number
): Promise<WordTimestamp[] | null> {
  const asrTargets = resolveTargetsForRole('voice_asr');
  for (const target of asrTargets) {
    const { profile, modelId } = target;
    if (!profile.baseUrl || !profile.apiKey) continue;

    try {
      const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol);
      const fileBuf = fs.readFileSync(mp3Path);
      const formData = new FormData();
      formData.append('file', new Blob([fileBuf], { type: 'audio/mpeg' }), path.basename(mp3Path));
      formData.append('model', modelId || 'whisper-1');
      formData.append('response_format', 'verbose_json');
      formData.append('timestamp_granularities[]', 'word');

      const resp = await fetch(`${baseUrl}/audio/transcriptions`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${profile.apiKey}`,
          ...profile.customHeaders,
        },
        body: formData,
        signal: AbortSignal.timeout(30000),
      });

      if (!resp.ok) continue;
      const data = (await resp.json()) as any;
      if (Array.isArray(data?.words) && data.words.length > 0) {
        return data.words.map((w: any) => ({
          word: String(w.word || '').trim(),
          start: Number(w.start || 0),
          end: Number(w.end || fallbackDurationSec),
        }));
      }
    } catch {
      // fallback to syllable timing
    }
  }
  return null;
}