@mux/ai 0.56.0 → 0.58.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/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // package.json
8
- var version = "0.56.0";
8
+ var version = "0.58.0";
9
9
 
10
10
  // src/lib/language-codes.ts
11
11
  var ISO639_1_TO_3 = {
@@ -117,8 +117,38 @@ var ISO639_1_TO_3 = {
117
117
  // Estonian
118
118
  lv: "lav",
119
119
  // Latvian
120
- lt: "lit"
120
+ lt: "lit",
121
121
  // Lithuanian
122
+ as: "asm",
123
+ az: "aze",
124
+ be: "bel",
125
+ bs: "bos",
126
+ cy: "cym",
127
+ ga: "gle",
128
+ ha: "hau",
129
+ hy: "hye",
130
+ jv: "jav",
131
+ ka: "kat",
132
+ kk: "kaz",
133
+ ky: "kir",
134
+ lb: "ltz",
135
+ ln: "lin",
136
+ mi: "mri",
137
+ mk: "mkd",
138
+ mn: "mon",
139
+ mt: "mlt",
140
+ my: "mya",
141
+ ne: "nep",
142
+ ny: "nya",
143
+ oc: "oci",
144
+ or: "ori",
145
+ ps: "pus",
146
+ sd: "snd",
147
+ so: "som",
148
+ sr: "srp",
149
+ tg: "tgk",
150
+ uz: "uzb",
151
+ yo: "yor"
122
152
  };
123
153
  var ISO639_3_TO_1 = Object.fromEntries(
124
154
  Object.entries(ISO639_1_TO_3).map(([iso1, iso3]) => [iso3, iso1])
@@ -135,7 +165,7 @@ function toISO639_1(code) {
135
165
  if (normalized.length === 2) {
136
166
  return normalized;
137
167
  }
138
- return ISO639_3_TO_1[normalized] ?? normalized;
168
+ return Object.prototype.hasOwnProperty.call(ISO639_3_TO_1, normalized) ? ISO639_3_TO_1[normalized] : normalized;
139
169
  }
140
170
  function getLanguageCodePair(code) {
141
171
  const normalized = code.toLowerCase().trim();
@@ -2904,6 +2934,11 @@ function isAudioOnlyAsset(asset) {
2904
2934
  const hasVideoTrack = asset.tracks?.some((track) => track.type === "video") ?? false;
2905
2935
  return hasAudioTrack && !hasVideoTrack;
2906
2936
  }
2937
+ function isVideoOnlyAsset(asset) {
2938
+ const hasAudioTrack = asset.tracks?.some((track) => track.type === "audio") ?? false;
2939
+ const hasVideoTrack = asset.tracks?.some((track) => track.type === "video") ?? false;
2940
+ return hasVideoTrack && !hasAudioTrack;
2941
+ }
2907
2942
  function toPlaybackAsset(asset) {
2908
2943
  const { id: playbackId, policy } = getPlaybackId(asset);
2909
2944
  return { asset, playbackId, policy };
@@ -9209,55 +9244,85 @@ import { sleep as sleep2 } from "workflow";
9209
9244
 
9210
9245
  // src/lib/elevenlabs-errors.ts
9211
9246
  var MAX_ERROR_BODY_CHARS = 500;
9212
- async function elevenLabsResponseError(context, response) {
9213
- const error = new Error(`${context}: ${await describeElevenLabsErrorResponse(response)}`);
9214
- if (!isRetryableElevenLabsStatus(response.status)) {
9215
- error.name = "FatalError";
9216
- }
9217
- return error;
9218
- }
9219
9247
  function isRetryableElevenLabsStatus(status) {
9220
9248
  return status === 408 || status === 425 || status === 429 || status >= 500;
9221
9249
  }
9222
- async function describeElevenLabsErrorResponse(response) {
9223
- const statusLine = [response.status, response.statusText].filter(Boolean).join(" ");
9250
+ async function elevenLabsResponseFailure(response) {
9224
9251
  const body = await response.text().catch(() => "");
9225
- const detail = formatElevenLabsErrorBody(body);
9226
- return detail ? `${statusLine}: ${detail}` : statusLine;
9252
+ return httpFailure(response.status, response.statusText, body);
9253
+ }
9254
+ function elevenLabsSdkFailure(error) {
9255
+ const failure = error;
9256
+ if (typeof failure?.statusCode === "number") {
9257
+ const body = typeof failure.body === "string" ? failure.body : JSON.stringify(failure.body ?? "");
9258
+ return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body);
9259
+ }
9260
+ const message = failure?.message ?? String(error);
9261
+ switch (failure?.name) {
9262
+ case "ElevenLabsTimeoutError":
9263
+ return { reason: "timeout", retryable: true, detail: message };
9264
+ // The SDK validates responses strictly: the API's response no longer matches
9265
+ // this SDK version, so the same call fails the same way.
9266
+ case "ParseError":
9267
+ return { reason: "unexpected_response", retryable: false, detail: `Unexpected ElevenLabs response: ${message}` };
9268
+ // The SDK's own error without a status: the request got no response.
9269
+ case "ElevenLabsError":
9270
+ return { reason: "network_error", retryable: true, detail: message };
9271
+ default:
9272
+ return { retryable: false, detail: message };
9273
+ }
9227
9274
  }
9228
- function formatElevenLabsErrorBody(body) {
9275
+ function httpFailure(status, statusText, body) {
9276
+ const statusLine = [status, statusText].filter(Boolean).join(" ");
9277
+ const { reason, detail } = parseElevenLabsErrorBody(body);
9278
+ return {
9279
+ httpStatus: status,
9280
+ reason,
9281
+ retryable: isRetryableElevenLabsStatus(status),
9282
+ detail: detail ? `${statusLine}: ${detail}` : statusLine
9283
+ };
9284
+ }
9285
+ function parseElevenLabsErrorBody(body) {
9229
9286
  const trimmed = body.trim();
9230
9287
  if (!trimmed) {
9231
- return "";
9288
+ return { detail: "" };
9232
9289
  }
9233
9290
  let detail;
9234
9291
  try {
9235
9292
  detail = JSON.parse(trimmed).detail;
9236
9293
  } catch {
9237
- return trimmed.slice(0, MAX_ERROR_BODY_CHARS);
9294
+ return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
9238
9295
  }
9239
9296
  if (typeof detail === "string" && detail) {
9240
- return detail;
9297
+ return { detail };
9241
9298
  }
9242
9299
  if (Array.isArray(detail) && detail.length > 0) {
9243
- return detail.map((item) => [item.loc?.join("."), item.msg].filter(Boolean).join(": ")).join("; ");
9300
+ return {
9301
+ detail: detail.map((item) => [item.loc?.join("."), item.msg].filter(Boolean).join(": ")).join("; ")
9302
+ };
9244
9303
  }
9245
9304
  if (detail && typeof detail === "object") {
9246
9305
  const { status, code, message, param, request_id: requestId } = detail;
9247
- const reason = [status ?? code, message].filter(Boolean).join(": ");
9306
+ const reasonCode = [status, code].find((value) => typeof value === "string" && value !== "");
9307
+ const reasonText = [reasonCode, message].filter(Boolean).join(": ");
9248
9308
  const context = [param && `param: ${param}`, requestId && `request_id: ${requestId}`].filter(Boolean).join(", ");
9249
- if (reason) {
9250
- return context ? `${reason} (${context})` : reason;
9309
+ if (reasonText) {
9310
+ return { reason: reasonCode, detail: context ? `${reasonText} (${context})` : reasonText };
9251
9311
  }
9252
9312
  }
9253
- return trimmed.slice(0, MAX_ERROR_BODY_CHARS);
9313
+ return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
9254
9314
  }
9255
9315
 
9256
9316
  // src/workflows/translate-audio.ts
9317
+ var CAPTIONS_UNAVAILABLE_MESSAGE = "The dub completed, but its subtitles could not be retrieved.";
9318
+ var CAPTIONS_ATTACHMENT_FAILED_MESSAGE = "Dub subtitles could not be attached to the Mux asset.";
9257
9319
  var STATIC_RENDITION_POLL_INTERVAL_MS = 1e4;
9258
9320
  var STATIC_RENDITION_MAX_ATTEMPTS = 180;
9259
9321
  var MAX_DUBBING_SOURCE_BYTES = 1e9;
9260
9322
  var DUBBING_POLL_INTERVAL_MS = 1e4;
9323
+ var MAX_CONSECUTIVE_STATUS_CHECK_FAILURES = 6;
9324
+ var DUBBED_AUDIO_DOWNLOAD_ATTEMPTS = 3;
9325
+ var DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS = 1e4;
9261
9326
  var DEFAULT_DUBBING_POLL_TIMEOUT_SECONDS = 7200;
9262
9327
  function getReadyAudioStaticRendition(asset) {
9263
9328
  const files = asset.static_renditions?.files;
@@ -9391,64 +9456,128 @@ async function waitForLegacyMp4SupportRendition({
9391
9456
  }
9392
9457
  return rendition.name;
9393
9458
  }
9459
+ function toBaseLanguageCode(code) {
9460
+ return code.trim().split(/[-_]/)[0];
9461
+ }
9462
+ function audioTrackUnsupportedReason(asset) {
9463
+ const useDubbedFile = "skip uploading to Mux and use the dubbed audio file directly.";
9464
+ if (asset.ingest_type === "on_demand_clip" || asset.source_asset_id) {
9465
+ return `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}`;
9466
+ }
9467
+ if (asset.is_live || asset.live_stream_id) {
9468
+ return `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}`;
9469
+ }
9470
+ if (isAudioOnlyAsset(asset)) {
9471
+ return `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}`;
9472
+ }
9473
+ return void 0;
9474
+ }
9475
+ function dubbingProviderError(message, failure) {
9476
+ if (failure.reason === "timeout") {
9477
+ return new MuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
9478
+ }
9479
+ if (failure.retryable) {
9480
+ return new MuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
9481
+ }
9482
+ return new MuxAiError(message, { type: "processing_error" });
9483
+ }
9484
+ function dubbingStartError(failure, languages) {
9485
+ if (failure.reason === "unsupported_target_language") {
9486
+ return new MuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
9487
+ }
9488
+ if (failure.reason === "unsupported_source_language" && languages.source) {
9489
+ return new MuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
9490
+ }
9491
+ return dubbingProviderError("Audio dubbing could not be started.", failure);
9492
+ }
9394
9493
  async function createElevenLabsDubbingJob({
9395
9494
  sourceUrl,
9396
9495
  assetId,
9397
9496
  elevenLabsLangCode,
9398
9497
  elevenLabsSourceLangCode,
9399
- numSpeakers,
9400
9498
  credentials
9401
9499
  }) {
9402
9500
  "use step";
9403
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9404
- const formData = new FormData();
9405
- formData.append("source_url", sourceUrl);
9406
- formData.append("target_lang", elevenLabsLangCode);
9407
- if (elevenLabsSourceLangCode) {
9408
- formData.append("source_lang", elevenLabsSourceLangCode);
9409
- }
9410
- formData.append("num_speakers", numSpeakers.toString());
9411
- formData.append(
9412
- "name",
9413
- `Mux Asset ${assetId} - ${elevenLabsSourceLangCode ?? "auto"} to ${elevenLabsLangCode}`
9414
- );
9415
- const dubbingResponse = await fetch("https://api.elevenlabs.io/v1/dubbing", {
9416
- method: "POST",
9417
- headers: {
9418
- "xi-api-key": elevenLabsApiKey
9419
- },
9420
- body: formData
9421
- });
9422
- if (!dubbingResponse.ok) {
9423
- throw await elevenLabsResponseError("ElevenLabs API error", dubbingResponse);
9501
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9502
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9503
+ try {
9504
+ const project = await client.dubbing.project.create({
9505
+ sourceUrl,
9506
+ sourceLanguage: elevenLabsSourceLangCode,
9507
+ targetLanguage: elevenLabsLangCode,
9508
+ modelId: "dubbing_v1",
9509
+ reference: `Mux Asset ${assetId} - ${elevenLabsSourceLangCode ?? "auto"} to ${elevenLabsLangCode}`
9510
+ });
9511
+ const languageId = project.languageIds?.[0];
9512
+ if (!languageId) {
9513
+ return {
9514
+ kind: "failed",
9515
+ failure: { retryable: false, detail: `ElevenLabs project ${project.projectId} returned no language target. Check the project before retrying.` }
9516
+ };
9517
+ }
9518
+ return { kind: "created", projectId: project.projectId, languageId };
9519
+ } catch (error) {
9520
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9424
9521
  }
9425
- const dubbingData = await dubbingResponse.json();
9426
- return dubbingData.dubbing_id;
9427
9522
  }
9428
9523
  async function checkElevenLabsDubbingStatus({
9429
9524
  dubbingId,
9525
+ languageId,
9430
9526
  credentials
9431
9527
  }) {
9432
9528
  "use step";
9433
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9434
- const statusResponse = await fetch(`https://api.elevenlabs.io/v1/dubbing/${dubbingId}`, {
9435
- headers: {
9436
- "xi-api-key": elevenLabsApiKey
9529
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9530
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9531
+ try {
9532
+ const [project, language] = await Promise.all([
9533
+ client.dubbing.project.get(dubbingId),
9534
+ client.dubbing.project.language.get(dubbingId, languageId)
9535
+ ]);
9536
+ return {
9537
+ kind: "status",
9538
+ status: project.status === "failed" ? "failed" : language.status,
9539
+ // A language error of `project_failed` only points at the project, so prefer the project's.
9540
+ error: project.error ?? language.error
9541
+ };
9542
+ } catch (error) {
9543
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9544
+ }
9545
+ }
9546
+ async function fetchDubbingOutput(dubbingId, languageId, output, credentials) {
9547
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9548
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9549
+ for (let attempt = 0; attempt < 2; attempt++) {
9550
+ let url;
9551
+ try {
9552
+ const target = await client.dubbing.project.language.get(dubbingId, languageId);
9553
+ url = target.outputs?.[output];
9554
+ } catch (error) {
9555
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9556
+ }
9557
+ if (!url) {
9558
+ return {
9559
+ kind: "failed",
9560
+ failure: { reason: "output_missing", retryable: true, detail: `ElevenLabs language ${languageId} of project ${dubbingId} has no ${output} output` }
9561
+ };
9562
+ }
9563
+ let response;
9564
+ try {
9565
+ response = await fetch(url);
9566
+ } catch (error) {
9567
+ return { kind: "failed", failure: { reason: "network_error", retryable: true, detail: `Failed to fetch dubbed ${output}: ${error instanceof Error ? error.message : String(error)}` } };
9568
+ }
9569
+ if (response.ok) {
9570
+ return { kind: "fetched", response, url };
9571
+ }
9572
+ if (response.status !== 403 || attempt === 1) {
9573
+ return { kind: "failed", failure: await elevenLabsResponseFailure(response) };
9437
9574
  }
9438
- });
9439
- if (!statusResponse.ok) {
9440
- throw await elevenLabsResponseError("Status check failed", statusResponse);
9441
9575
  }
9442
- const statusData = await statusResponse.json();
9443
- return {
9444
- status: statusData.status,
9445
- targetLanguages: statusData.target_languages ?? [],
9446
- error: typeof statusData.error === "string" && statusData.error ? statusData.error : void 0
9447
- };
9576
+ return { kind: "failed", failure: { retryable: false, detail: `Failed to fetch dubbed ${output}` } };
9448
9577
  }
9449
9578
  async function downloadAndUploadDubbedAudio({
9450
9579
  dubbingId,
9451
- languageCode,
9580
+ languageId,
9452
9581
  assetId,
9453
9582
  toLanguageCode,
9454
9583
  s3Endpoint,
@@ -9459,20 +9588,32 @@ async function downloadAndUploadDubbedAudio({
9459
9588
  credentials
9460
9589
  }) {
9461
9590
  "use step";
9462
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9463
- const audioUrl = `https://api.elevenlabs.io/v1/dubbing/${dubbingId}/audio/${languageCode}`;
9464
- const audioResponse = await fetch(audioUrl, {
9465
- headers: {
9466
- "xi-api-key": elevenLabsApiKey
9467
- }
9468
- });
9469
- if (!audioResponse.ok) {
9470
- throw await elevenLabsResponseError("Failed to fetch dubbed audio", audioResponse);
9591
+ const fetched = await fetchDubbingOutput(dubbingId, languageId, "losslessAudio", credentials);
9592
+ if (fetched.kind === "failed") {
9593
+ return fetched;
9594
+ }
9595
+ const { response: audioResponse, url } = fetched;
9596
+ const mime = audioResponse.headers.get("content-type")?.split(";")[0].trim();
9597
+ const formats = {
9598
+ "audio/flac": "flac",
9599
+ "audio/x-flac": "flac",
9600
+ "audio/wav": "wav",
9601
+ "audio/x-wav": "wav",
9602
+ "audio/mp4": "m4a",
9603
+ "audio/mpeg": "mp3"
9604
+ };
9605
+ const pathExtension = new URL(url).pathname.split(".").pop()?.toLowerCase();
9606
+ const extension = (mime ? formats[mime] : void 0) ?? Object.values(formats).find((format) => format === pathExtension);
9607
+ if (!extension) {
9608
+ return {
9609
+ kind: "failed",
9610
+ failure: { reason: "unsupported_output_format", retryable: false, detail: `Unsupported dubbed audio content type: ${mime ?? "missing"}` }
9611
+ };
9471
9612
  }
9472
9613
  const dubbedAudio = new Uint8Array(await audioResponse.arrayBuffer());
9473
9614
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9474
9615
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9475
- const audioKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.m4a`;
9616
+ const audioKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.${extension}`;
9476
9617
  await putObjectWithStorageAdapter({
9477
9618
  accessKeyId: s3AccessKeyId,
9478
9619
  secretAccessKey: s3SecretAccessKey,
@@ -9481,7 +9622,7 @@ async function downloadAndUploadDubbedAudio({
9481
9622
  bucket: s3Bucket,
9482
9623
  key: audioKey,
9483
9624
  body: dubbedAudio,
9484
- contentType: "audio/mp4"
9625
+ contentType: Object.keys(formats).find((type) => formats[type] === extension)
9485
9626
  }, storageAdapter);
9486
9627
  const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9487
9628
  accessKeyId: s3AccessKeyId,
@@ -9495,11 +9636,11 @@ async function downloadAndUploadDubbedAudio({
9495
9636
  const expiryHours = Math.round((s3SignedUrlExpirySeconds ?? 86400) / 3600);
9496
9637
  console.warn(`\u2705 Audio uploaded successfully to: ${audioKey}`);
9497
9638
  console.warn(`\u{1F517} Generated presigned URL (expires in ${expiryHours} hour${expiryHours === 1 ? "" : "s"})`);
9498
- return presignedUrl;
9639
+ return { kind: "staged", presignedUrl };
9499
9640
  }
9500
9641
  async function downloadAndUploadDubTranscript({
9501
9642
  dubbingId,
9502
- languageCode,
9643
+ languageId,
9503
9644
  assetId,
9504
9645
  toLanguageCode,
9505
9646
  s3Endpoint,
@@ -9510,45 +9651,56 @@ async function downloadAndUploadDubTranscript({
9510
9651
  credentials
9511
9652
  }) {
9512
9653
  "use step";
9513
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9514
- const transcriptUrl = `https://api.elevenlabs.io/v1/dubbing/${dubbingId}/transcripts/${languageCode}/format/webvtt`;
9515
- const transcriptResponse = await fetch(transcriptUrl, {
9516
- headers: {
9517
- "xi-api-key": elevenLabsApiKey
9518
- }
9519
- });
9520
- if (!transcriptResponse.ok) {
9521
- throw await elevenLabsResponseError("Failed to fetch dub transcript", transcriptResponse);
9654
+ try {
9655
+ const fetched = await fetchDubbingOutput(dubbingId, languageId, "subtitles", credentials);
9656
+ if (fetched.kind === "failed") {
9657
+ return fetched;
9658
+ }
9659
+ const transcriptVtt = await fetched.response.text();
9660
+ if (!transcriptVtt.trim()) {
9661
+ return { kind: "failed", failure: { retryable: false, detail: "Dub transcript response did not include webvtt content" } };
9662
+ }
9663
+ const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9664
+ const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9665
+ const vttKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.vtt`;
9666
+ await putObjectWithStorageAdapter({
9667
+ accessKeyId: s3AccessKeyId,
9668
+ secretAccessKey: s3SecretAccessKey,
9669
+ endpoint: s3Endpoint,
9670
+ region: s3Region,
9671
+ bucket: s3Bucket,
9672
+ key: vttKey,
9673
+ body: transcriptVtt,
9674
+ contentType: "text/vtt"
9675
+ }, storageAdapter);
9676
+ const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9677
+ accessKeyId: s3AccessKeyId,
9678
+ secretAccessKey: s3SecretAccessKey,
9679
+ endpoint: s3Endpoint,
9680
+ region: s3Region,
9681
+ bucket: s3Bucket,
9682
+ key: vttKey,
9683
+ expiresInSeconds: s3SignedUrlExpirySeconds ?? 86400
9684
+ }, storageAdapter);
9685
+ console.warn(`\u2705 Dub transcript uploaded successfully to: ${vttKey}`);
9686
+ return { kind: "staged", presignedUrl };
9687
+ } catch (error) {
9688
+ return { kind: "failed", failure: { retryable: true, detail: extractErrorDetail(error) } };
9522
9689
  }
9523
- const transcriptBody = await transcriptResponse.json();
9524
- const transcriptVtt = transcriptBody.webvtt;
9525
- if (!transcriptVtt) {
9526
- throw new Error("Dub transcript response did not include webvtt content");
9690
+ }
9691
+ async function attachDubbedCaptions(input) {
9692
+ "use step";
9693
+ try {
9694
+ const outcome = await replaceAndCreateTrack(input);
9695
+ if (outcome.kind === "created") {
9696
+ return { status: "created", trackId: outcome.trackId, replacedTracks: outcome.deleted };
9697
+ }
9698
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${outcome.reason}`);
9699
+ return { status: "failed", message: outcome.kind === "blocked" ? outcome.reason : CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: outcome.kind === "create_failed", replacedTracks: outcome.deleted };
9700
+ } catch (error) {
9701
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${extractErrorDetail(error)}`);
9702
+ return { status: "failed", message: CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: true, replacedTracks: [] };
9527
9703
  }
9528
- const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9529
- const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9530
- const vttKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.vtt`;
9531
- await putObjectWithStorageAdapter({
9532
- accessKeyId: s3AccessKeyId,
9533
- secretAccessKey: s3SecretAccessKey,
9534
- endpoint: s3Endpoint,
9535
- region: s3Region,
9536
- bucket: s3Bucket,
9537
- key: vttKey,
9538
- body: transcriptVtt,
9539
- contentType: "text/vtt"
9540
- }, storageAdapter);
9541
- const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9542
- accessKeyId: s3AccessKeyId,
9543
- secretAccessKey: s3SecretAccessKey,
9544
- endpoint: s3Endpoint,
9545
- region: s3Region,
9546
- bucket: s3Bucket,
9547
- key: vttKey,
9548
- expiresInSeconds: s3SignedUrlExpirySeconds ?? 86400
9549
- }, storageAdapter);
9550
- console.warn(`\u2705 Dub transcript uploaded successfully to: ${vttKey}`);
9551
- return presignedUrl;
9552
9704
  }
9553
9705
  async function translateAudio(assetId, toLanguageCode, options = {}) {
9554
9706
  "use workflow";
@@ -9564,21 +9716,26 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9564
9716
  storageAdapter,
9565
9717
  credentials: providedCredentials,
9566
9718
  replaceExistingTracks = "fail",
9719
+ captionsReplaceExistingTracks = replaceExistingTracks,
9567
9720
  trackName: providedTrackName,
9568
9721
  trackPassthrough: providedTrackPassthrough
9569
9722
  } = options;
9570
9723
  if (provider !== "elevenlabs") {
9571
9724
  throw new MuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
9572
9725
  }
9726
+ const targetLanguageCode = toISO639_1(toLanguageCode);
9727
+ if (numSpeakers !== 0) {
9728
+ throw new MuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
9729
+ }
9573
9730
  const credentials = providedCredentials;
9574
9731
  const effectiveStorageAdapter = storageAdapter;
9575
9732
  const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("translate-audio");
9576
9733
  const uploadToMux = uploadToMuxOption !== false;
9577
9734
  const uploadToS3 = uploadToS3Option || uploadToMux || uploadCaptionsToMux;
9578
- const muxLangCode = toISO639_1(toLanguageCode);
9735
+ const muxLangCode = targetLanguageCode;
9579
9736
  const trackName = providedTrackName ?? `${getLanguageName(muxLangCode) ?? muxLangCode.toUpperCase()} (Auto-dubbed)`;
9580
9737
  const audioTrackTarget = { type: "audio", languageCode: muxLangCode, name: trackName };
9581
- const captionsTrackTarget = { type: "text", languageCode: muxLangCode, name: trackName };
9738
+ const captionsTrackTarget = { type: "text", languageCode: muxLangCode, name: options.captionsTrackName ?? trackName };
9582
9739
  const s3Endpoint = options.s3Endpoint ?? env_default.S3_ENDPOINT;
9583
9740
  const s3Region = options.s3Region ?? env_default.S3_REGION ?? "auto";
9584
9741
  const s3Bucket = options.s3Bucket ?? env_default.S3_BUCKET;
@@ -9589,11 +9746,15 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9589
9746
  }
9590
9747
  const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
9591
9748
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(initialAsset);
9592
- for (const target of [
9593
- ...uploadToMux ? [audioTrackTarget] : [],
9594
- ...uploadCaptionsToMux ? [captionsTrackTarget] : []
9595
- ]) {
9596
- const plan = planTextTrackReplacement(initialAsset, target, replaceExistingTracks);
9749
+ if (isVideoOnlyAsset(initialAsset)) {
9750
+ throw new MuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
9751
+ }
9752
+ const audioTrackUnsupported = uploadToMux ? audioTrackUnsupportedReason(initialAsset) : void 0;
9753
+ if (audioTrackUnsupported) {
9754
+ throw new MuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
9755
+ }
9756
+ if (uploadToMux) {
9757
+ const plan = planTextTrackReplacement(initialAsset, audioTrackTarget, replaceExistingTracks);
9597
9758
  if (plan.kind === "blocked") {
9598
9759
  throw new MuxAiError(plan.reason, { type: "validation_error" });
9599
9760
  }
@@ -9612,11 +9773,13 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9612
9773
  }
9613
9774
  let staticRenditionCleanup = "not_created";
9614
9775
  let dubbingId;
9776
+ let languageId;
9615
9777
  let presignedUrl;
9616
9778
  let uploadedTrackId;
9617
9779
  let replacedTracks;
9618
9780
  let captionsPresignedUrl;
9619
9781
  let captionsTrackId;
9782
+ let captionsOutcome;
9620
9783
  try {
9621
9784
  let sourceRenditionName = "audio.m4a";
9622
9785
  if (isLegacyMp4SupportAsset) {
@@ -9646,75 +9809,114 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9646
9809
  audioUrl = await signUrl(audioUrl, playbackId, "video", void 0, credentials);
9647
9810
  }
9648
9811
  console.warn("\u{1F399}\uFE0F Creating dubbing job in ElevenLabs...");
9649
- const elevenLabsLangCode = toISO639_3(toLanguageCode);
9650
- const normalizedFromLanguageCode = fromLanguageCode?.trim();
9651
- const elevenLabsSourceLangCode = normalizedFromLanguageCode ? toISO639_3(normalizedFromLanguageCode) : void 0;
9812
+ const elevenLabsLangCode = toISO639_1(toBaseLanguageCode(toLanguageCode));
9813
+ const sourceLanguageCode = toISO639_1(toBaseLanguageCode(fromLanguageCode ?? "auto"));
9814
+ const elevenLabsSourceLangCode = sourceLanguageCode && sourceLanguageCode !== "auto" ? sourceLanguageCode : void 0;
9652
9815
  console.warn(
9653
9816
  `\u{1F50D} Creating dubbing job for asset ${assetId}: ${elevenLabsSourceLangCode ?? "auto"} -> ${elevenLabsLangCode}`
9654
9817
  );
9818
+ let created;
9655
9819
  try {
9656
- dubbingId = await createElevenLabsDubbingJob({
9820
+ created = await createElevenLabsDubbingJob({
9657
9821
  sourceUrl: audioUrl,
9658
9822
  assetId,
9659
9823
  elevenLabsLangCode,
9660
9824
  elevenLabsSourceLangCode,
9661
- numSpeakers,
9662
9825
  credentials
9663
9826
  });
9664
- console.warn(`\u2705 Dubbing job created with ID: ${dubbingId}`);
9665
9827
  } catch (error) {
9666
9828
  wrapError(error, "Failed to create ElevenLabs dubbing job");
9667
9829
  }
9830
+ if (created.kind === "failed") {
9831
+ const { failure } = created;
9832
+ const mayHaveCreated = failure.reason === "timeout" || failure.reason === "network_error" || failure.reason === "unexpected_response";
9833
+ console.warn(
9834
+ `Failed to create ElevenLabs dubbing project for asset ${assetId}: ${failure.detail}${mayHaveCreated ? " The project may have been created; check ElevenLabs before retrying." : ""}`
9835
+ );
9836
+ throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode });
9837
+ }
9838
+ dubbingId = created.projectId;
9839
+ languageId = created.languageId;
9840
+ console.warn(`\u2705 Dubbing job created with ID: ${dubbingId}`);
9668
9841
  console.warn("\u23F3 Waiting for dubbing to complete...");
9669
9842
  const dubbingPollTimeoutSeconds = options.dubbingPollTimeoutSeconds ?? DEFAULT_DUBBING_POLL_TIMEOUT_SECONDS;
9670
9843
  const maxPollAttempts = Math.max(1, Math.ceil(dubbingPollTimeoutSeconds * 1e3 / DUBBING_POLL_INTERVAL_MS));
9671
9844
  let dubbingStatus = "dubbing";
9672
9845
  let pollAttempts = 0;
9673
- let targetLanguages = [];
9674
9846
  let dubbingError;
9675
- while (dubbingStatus !== "dubbed" && pollAttempts < maxPollAttempts) {
9847
+ let consecutiveStatusCheckFailures = 0;
9848
+ while (dubbingStatus !== "completed" && pollAttempts < maxPollAttempts) {
9676
9849
  await sleep2(DUBBING_POLL_INTERVAL_MS);
9677
9850
  pollAttempts++;
9851
+ let statusResult;
9678
9852
  try {
9679
- const statusResult = await checkElevenLabsDubbingStatus({
9853
+ statusResult = await checkElevenLabsDubbingStatus({
9680
9854
  dubbingId,
9855
+ languageId,
9681
9856
  credentials
9682
9857
  });
9683
- dubbingStatus = statusResult.status;
9684
- targetLanguages = statusResult.targetLanguages;
9685
- dubbingError = statusResult.error;
9686
9858
  } catch (error) {
9687
9859
  wrapError(error, "Failed to check dubbing status");
9688
9860
  }
9861
+ if (statusResult.kind === "failed") {
9862
+ const { failure } = statusResult;
9863
+ consecutiveStatusCheckFailures++;
9864
+ console.warn(`Status check for ElevenLabs dubbing project ${dubbingId} failed: ${failure.detail}`);
9865
+ if (!failure.retryable || consecutiveStatusCheckFailures >= MAX_CONSECUTIVE_STATUS_CHECK_FAILURES) {
9866
+ throw dubbingProviderError("Could not check audio dubbing progress.", failure);
9867
+ }
9868
+ continue;
9869
+ }
9870
+ consecutiveStatusCheckFailures = 0;
9871
+ dubbingStatus = statusResult.status;
9872
+ dubbingError = statusResult.error;
9689
9873
  if (dubbingStatus === "failed") {
9690
- console.warn(`\u274C ElevenLabs dubbing job ${dubbingId} failed: ${dubbingError ?? "no error reported"}`);
9691
- throw new MuxAiError("ElevenLabs reported that the dubbing job failed.", { type: "processing_error" });
9874
+ console.warn(`\u274C ElevenLabs dubbing project ${dubbingId} (language ${languageId}) failed: ${dubbingError ? `${dubbingError.code}: ${dubbingError.message}` : "no error reported"}`);
9875
+ if (!dubbingError) {
9876
+ throw new MuxAiError("Audio dubbing failed.", { type: "processing_error" });
9877
+ }
9878
+ throw new MuxAiError(
9879
+ `Audio dubbing failed: ${dubbingError.message}${dubbingError.retryable ? " Please try again." : ""}`,
9880
+ { type: "processing_error", retryable: dubbingError.retryable }
9881
+ );
9692
9882
  }
9693
9883
  }
9694
- if (dubbingStatus !== "dubbed") {
9884
+ if (dubbingStatus !== "completed") {
9695
9885
  throw new MuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
9696
9886
  }
9697
9887
  console.warn("\u2705 Dubbing completed successfully!");
9698
9888
  if (uploadToS3) {
9699
9889
  console.warn("\u{1F4E5} Downloading dubbed audio from ElevenLabs and staging to S3...");
9700
- const downloadLangCode = targetLanguages[0] ?? toISO639_1(toLanguageCode);
9701
- try {
9702
- presignedUrl = await downloadAndUploadDubbedAudio({
9703
- dubbingId,
9704
- languageCode: downloadLangCode,
9705
- assetId,
9706
- toLanguageCode,
9707
- s3Endpoint,
9708
- s3Region,
9709
- s3Bucket,
9710
- storageAdapter: effectiveStorageAdapter,
9711
- s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9712
- credentials
9713
- });
9714
- console.warn("\u2705 Dubbed audio staged to S3 successfully!");
9715
- } catch (error) {
9716
- wrapError(error, "Failed to download and upload dubbed audio");
9890
+ for (let attempt = 1; !presignedUrl; attempt++) {
9891
+ let staged;
9892
+ try {
9893
+ staged = await downloadAndUploadDubbedAudio({
9894
+ dubbingId,
9895
+ languageId,
9896
+ assetId,
9897
+ toLanguageCode,
9898
+ s3Endpoint,
9899
+ s3Region,
9900
+ s3Bucket,
9901
+ storageAdapter: effectiveStorageAdapter,
9902
+ s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9903
+ credentials
9904
+ });
9905
+ } catch (error) {
9906
+ wrapError(error, "Failed to download and upload dubbed audio");
9907
+ }
9908
+ if (staged.kind === "staged") {
9909
+ presignedUrl = staged.presignedUrl;
9910
+ break;
9911
+ }
9912
+ const { failure } = staged;
9913
+ console.warn(`Downloading dubbed audio for ElevenLabs dubbing project ${dubbingId} failed (attempt ${attempt}): ${failure.detail}`);
9914
+ if (!failure.retryable || attempt >= DUBBED_AUDIO_DOWNLOAD_ATTEMPTS) {
9915
+ throw dubbingProviderError("Could not download the dubbed audio.", failure);
9916
+ }
9917
+ await sleep2(DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS);
9717
9918
  }
9919
+ console.warn("\u2705 Dubbed audio staged to S3 successfully!");
9718
9920
  if (uploadToMux) {
9719
9921
  console.warn("\u{1F4F9} Adding dubbed audio track to Mux asset...");
9720
9922
  let outcome;
@@ -9743,9 +9945,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9743
9945
  }
9744
9946
  try {
9745
9947
  console.warn("\u{1F4E5} Downloading dub transcript from ElevenLabs and staging to S3...");
9746
- captionsPresignedUrl = await downloadAndUploadDubTranscript({
9948
+ const transcript = await downloadAndUploadDubTranscript({
9747
9949
  dubbingId,
9748
- languageCode: downloadLangCode,
9950
+ languageId,
9749
9951
  assetId,
9750
9952
  toLanguageCode,
9751
9953
  s3Endpoint,
@@ -9755,27 +9957,36 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9755
9957
  s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9756
9958
  credentials
9757
9959
  });
9758
- if (uploadCaptionsToMux) {
9960
+ if (transcript.kind === "failed") {
9961
+ captionsOutcome = { status: "unavailable", message: CAPTIONS_UNAVAILABLE_MESSAGE, retryable: transcript.failure.retryable };
9962
+ console.warn(`\u26A0\uFE0F Failed to retrieve dubbed captions: ${transcript.failure.detail}`);
9963
+ } else {
9964
+ captionsPresignedUrl = transcript.presignedUrl;
9965
+ captionsOutcome = { status: "available" };
9966
+ }
9967
+ if (uploadCaptionsToMux && captionsPresignedUrl) {
9759
9968
  console.warn("\u{1F4F9} Adding dubbed captions track to Mux asset...");
9760
- const captionsOutcome = await replaceAndCreateTrack({
9969
+ captionsOutcome = await attachDubbedCaptions({
9761
9970
  assetId,
9762
9971
  target: captionsTrackTarget,
9763
- policy: replaceExistingTracks,
9972
+ policy: captionsReplaceExistingTracks,
9764
9973
  presignedUrl: captionsPresignedUrl,
9765
9974
  passthrough: trackPassthrough,
9766
9975
  credentials
9767
9976
  });
9768
- if (captionsOutcome.deleted.length > 0) {
9769
- replacedTracks = [...replacedTracks ?? [], ...captionsOutcome.deleted];
9977
+ if (captionsOutcome.replacedTracks.length > 0) {
9978
+ replacedTracks = [...replacedTracks ?? [], ...captionsOutcome.replacedTracks];
9770
9979
  }
9771
- if (captionsOutcome.kind !== "created") {
9772
- throw new Error(captionsOutcome.reason);
9980
+ if (captionsOutcome.status === "created") {
9981
+ captionsTrackId = captionsOutcome.trackId;
9982
+ console.warn(`\u2705 Captions track added to Mux asset with ID: ${captionsTrackId}`);
9983
+ } else {
9984
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${captionsOutcome.message}`);
9773
9985
  }
9774
- captionsTrackId = captionsOutcome.trackId;
9775
- console.warn(`\u2705 Captions track added to Mux asset with ID: ${captionsTrackId}`);
9776
9986
  }
9777
9987
  } catch (error) {
9778
- console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${error instanceof Error ? error.message : "Unknown error"}`);
9988
+ captionsOutcome = captionsPresignedUrl ? { status: "failed", message: CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: true, replacedTracks: [] } : { status: "unavailable", message: CAPTIONS_UNAVAILABLE_MESSAGE, retryable: true };
9989
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${extractErrorDetail(error)}`);
9779
9990
  if (captionsPresignedUrl) {
9780
9991
  console.warn("\u{1F517} You can manually add the captions track using this presigned URL:");
9781
9992
  console.warn(captionsPresignedUrl);
@@ -9794,10 +10005,10 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9794
10005
  }
9795
10006
  }
9796
10007
  }
9797
- const targetLanguage = getLanguageCodePair(toLanguageCode);
10008
+ const targetLanguage = getLanguageCodePair(targetLanguageCode);
9798
10009
  return {
9799
10010
  assetId,
9800
- targetLanguageCode: targetLanguage.iso639_1,
10011
+ targetLanguageCode,
9801
10012
  targetLanguage,
9802
10013
  dubbingId,
9803
10014
  uploadedTrackId,
@@ -9805,6 +10016,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9805
10016
  replacedTracks,
9806
10017
  captionsTrackId,
9807
10018
  captionsPresignedUrl,
10019
+ captionsOutcome,
9808
10020
  createdStaticRenditionId,
9809
10021
  staticRenditionCleanup,
9810
10022
  usage: {