@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.
@@ -2029,6 +2029,11 @@ function isAudioOnlyAsset(asset) {
2029
2029
  const hasVideoTrack = asset.tracks?.some((track) => track.type === "video") ?? false;
2030
2030
  return hasAudioTrack && !hasVideoTrack;
2031
2031
  }
2032
+ function isVideoOnlyAsset(asset) {
2033
+ const hasAudioTrack = asset.tracks?.some((track) => track.type === "audio") ?? false;
2034
+ const hasVideoTrack = asset.tracks?.some((track) => track.type === "video") ?? false;
2035
+ return hasVideoTrack && !hasAudioTrack;
2036
+ }
2032
2037
  function toPlaybackAsset(asset) {
2033
2038
  const { id: playbackId, policy } = getPlaybackId(asset);
2034
2039
  return { asset, playbackId, policy };
@@ -2440,8 +2445,38 @@ var ISO639_1_TO_3 = {
2440
2445
  // Estonian
2441
2446
  lv: "lav",
2442
2447
  // Latvian
2443
- lt: "lit"
2448
+ lt: "lit",
2444
2449
  // Lithuanian
2450
+ as: "asm",
2451
+ az: "aze",
2452
+ be: "bel",
2453
+ bs: "bos",
2454
+ cy: "cym",
2455
+ ga: "gle",
2456
+ ha: "hau",
2457
+ hy: "hye",
2458
+ jv: "jav",
2459
+ ka: "kat",
2460
+ kk: "kaz",
2461
+ ky: "kir",
2462
+ lb: "ltz",
2463
+ ln: "lin",
2464
+ mi: "mri",
2465
+ mk: "mkd",
2466
+ mn: "mon",
2467
+ mt: "mlt",
2468
+ my: "mya",
2469
+ ne: "nep",
2470
+ ny: "nya",
2471
+ oc: "oci",
2472
+ or: "ori",
2473
+ ps: "pus",
2474
+ sd: "snd",
2475
+ so: "som",
2476
+ sr: "srp",
2477
+ tg: "tgk",
2478
+ uz: "uzb",
2479
+ yo: "yor"
2445
2480
  };
2446
2481
  var ISO639_3_TO_1 = Object.fromEntries(
2447
2482
  Object.entries(ISO639_1_TO_3).map(([iso1, iso3]) => [iso3, iso1])
@@ -2458,7 +2493,7 @@ function toISO639_1(code) {
2458
2493
  if (normalized.length === 2) {
2459
2494
  return normalized;
2460
2495
  }
2461
- return ISO639_3_TO_1[normalized] ?? normalized;
2496
+ return Object.prototype.hasOwnProperty.call(ISO639_3_TO_1, normalized) ? ISO639_3_TO_1[normalized] : normalized;
2462
2497
  }
2463
2498
  function getLanguageCodePair(code) {
2464
2499
  const normalized = code.toLowerCase().trim();
@@ -8813,48 +8848,73 @@ import { sleep } from "workflow";
8813
8848
 
8814
8849
  // src/lib/elevenlabs-errors.ts
8815
8850
  var MAX_ERROR_BODY_CHARS = 500;
8816
- async function elevenLabsResponseError(context, response) {
8817
- const error = new Error(`${context}: ${await describeElevenLabsErrorResponse(response)}`);
8818
- if (!isRetryableElevenLabsStatus(response.status)) {
8819
- error.name = "FatalError";
8820
- }
8821
- return error;
8822
- }
8823
8851
  function isRetryableElevenLabsStatus(status) {
8824
8852
  return status === 408 || status === 425 || status === 429 || status >= 500;
8825
8853
  }
8826
- async function describeElevenLabsErrorResponse(response) {
8827
- const statusLine = [response.status, response.statusText].filter(Boolean).join(" ");
8854
+ async function elevenLabsResponseFailure(response) {
8828
8855
  const body = await response.text().catch(() => "");
8829
- const detail = formatElevenLabsErrorBody(body);
8830
- return detail ? `${statusLine}: ${detail}` : statusLine;
8856
+ return httpFailure(response.status, response.statusText, body);
8857
+ }
8858
+ function elevenLabsSdkFailure(error) {
8859
+ const failure = error;
8860
+ if (typeof failure?.statusCode === "number") {
8861
+ const body = typeof failure.body === "string" ? failure.body : JSON.stringify(failure.body ?? "");
8862
+ return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body);
8863
+ }
8864
+ const message = failure?.message ?? String(error);
8865
+ switch (failure?.name) {
8866
+ case "ElevenLabsTimeoutError":
8867
+ return { reason: "timeout", retryable: true, detail: message };
8868
+ // The SDK validates responses strictly: the API's response no longer matches
8869
+ // this SDK version, so the same call fails the same way.
8870
+ case "ParseError":
8871
+ return { reason: "unexpected_response", retryable: false, detail: `Unexpected ElevenLabs response: ${message}` };
8872
+ // The SDK's own error without a status: the request got no response.
8873
+ case "ElevenLabsError":
8874
+ return { reason: "network_error", retryable: true, detail: message };
8875
+ default:
8876
+ return { retryable: false, detail: message };
8877
+ }
8831
8878
  }
8832
- function formatElevenLabsErrorBody(body) {
8879
+ function httpFailure(status, statusText, body) {
8880
+ const statusLine = [status, statusText].filter(Boolean).join(" ");
8881
+ const { reason, detail } = parseElevenLabsErrorBody(body);
8882
+ return {
8883
+ httpStatus: status,
8884
+ reason,
8885
+ retryable: isRetryableElevenLabsStatus(status),
8886
+ detail: detail ? `${statusLine}: ${detail}` : statusLine
8887
+ };
8888
+ }
8889
+ function parseElevenLabsErrorBody(body) {
8833
8890
  const trimmed = body.trim();
8834
8891
  if (!trimmed) {
8835
- return "";
8892
+ return { detail: "" };
8836
8893
  }
8837
8894
  let detail;
8838
8895
  try {
8839
8896
  detail = JSON.parse(trimmed).detail;
8840
8897
  } catch {
8841
- return trimmed.slice(0, MAX_ERROR_BODY_CHARS);
8898
+ return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
8842
8899
  }
8843
8900
  if (typeof detail === "string" && detail) {
8844
- return detail;
8901
+ return { detail };
8845
8902
  }
8846
8903
  if (Array.isArray(detail) && detail.length > 0) {
8847
- return detail.map((item) => [item.loc?.join("."), item.msg].filter(Boolean).join(": ")).join("; ");
8904
+ return {
8905
+ detail: detail.map((item) => [item.loc?.join("."), item.msg].filter(Boolean).join(": ")).join("; ")
8906
+ };
8848
8907
  }
8849
8908
  if (detail && typeof detail === "object") {
8850
8909
  const { status, code, message, param, request_id: requestId } = detail;
8851
- const reason = [status ?? code, message].filter(Boolean).join(": ");
8910
+ const reasonCode = [status, code].find((value) => typeof value === "string" && value !== "");
8911
+ const reasonText = [reasonCode, message].filter(Boolean).join(": ");
8852
8912
  const context = [param && `param: ${param}`, requestId && `request_id: ${requestId}`].filter(Boolean).join(", ");
8853
- if (reason) {
8854
- return context ? `${reason} (${context})` : reason;
8913
+ if (reasonText) {
8914
+ return { reason: reasonCode, detail: context ? `${reasonText} (${context})` : reasonText };
8855
8915
  }
8856
8916
  }
8857
- return trimmed.slice(0, MAX_ERROR_BODY_CHARS);
8917
+ return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
8858
8918
  }
8859
8919
 
8860
8920
  // src/lib/mux-static-renditions.ts
@@ -8910,10 +8970,15 @@ function getLegacyMp4SupportRenditionSizeError(rendition, maxBytes) {
8910
8970
  }
8911
8971
 
8912
8972
  // src/workflows/translate-audio.ts
8973
+ var CAPTIONS_UNAVAILABLE_MESSAGE = "The dub completed, but its subtitles could not be retrieved.";
8974
+ var CAPTIONS_ATTACHMENT_FAILED_MESSAGE = "Dub subtitles could not be attached to the Mux asset.";
8913
8975
  var STATIC_RENDITION_POLL_INTERVAL_MS = 1e4;
8914
8976
  var STATIC_RENDITION_MAX_ATTEMPTS = 180;
8915
8977
  var MAX_DUBBING_SOURCE_BYTES = 1e9;
8916
8978
  var DUBBING_POLL_INTERVAL_MS = 1e4;
8979
+ var MAX_CONSECUTIVE_STATUS_CHECK_FAILURES = 6;
8980
+ var DUBBED_AUDIO_DOWNLOAD_ATTEMPTS = 3;
8981
+ var DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS = 1e4;
8917
8982
  var DEFAULT_DUBBING_POLL_TIMEOUT_SECONDS = 7200;
8918
8983
  function getReadyAudioStaticRendition(asset) {
8919
8984
  const files = asset.static_renditions?.files;
@@ -9047,64 +9112,128 @@ async function waitForLegacyMp4SupportRendition({
9047
9112
  }
9048
9113
  return rendition.name;
9049
9114
  }
9115
+ function toBaseLanguageCode(code) {
9116
+ return code.trim().split(/[-_]/)[0];
9117
+ }
9118
+ function audioTrackUnsupportedReason(asset) {
9119
+ const useDubbedFile = "skip uploading to Mux and use the dubbed audio file directly.";
9120
+ if (asset.ingest_type === "on_demand_clip" || asset.source_asset_id) {
9121
+ return `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}`;
9122
+ }
9123
+ if (asset.is_live || asset.live_stream_id) {
9124
+ return `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}`;
9125
+ }
9126
+ if (isAudioOnlyAsset(asset)) {
9127
+ return `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}`;
9128
+ }
9129
+ return void 0;
9130
+ }
9131
+ function dubbingProviderError(message, failure) {
9132
+ if (failure.reason === "timeout") {
9133
+ return new MuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
9134
+ }
9135
+ if (failure.retryable) {
9136
+ return new MuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
9137
+ }
9138
+ return new MuxAiError(message, { type: "processing_error" });
9139
+ }
9140
+ function dubbingStartError(failure, languages) {
9141
+ if (failure.reason === "unsupported_target_language") {
9142
+ return new MuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
9143
+ }
9144
+ if (failure.reason === "unsupported_source_language" && languages.source) {
9145
+ return new MuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
9146
+ }
9147
+ return dubbingProviderError("Audio dubbing could not be started.", failure);
9148
+ }
9050
9149
  async function createElevenLabsDubbingJob({
9051
9150
  sourceUrl,
9052
9151
  assetId,
9053
9152
  elevenLabsLangCode,
9054
9153
  elevenLabsSourceLangCode,
9055
- numSpeakers,
9056
9154
  credentials
9057
9155
  }) {
9058
9156
  "use step";
9059
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9060
- const formData = new FormData();
9061
- formData.append("source_url", sourceUrl);
9062
- formData.append("target_lang", elevenLabsLangCode);
9063
- if (elevenLabsSourceLangCode) {
9064
- formData.append("source_lang", elevenLabsSourceLangCode);
9065
- }
9066
- formData.append("num_speakers", numSpeakers.toString());
9067
- formData.append(
9068
- "name",
9069
- `Mux Asset ${assetId} - ${elevenLabsSourceLangCode ?? "auto"} to ${elevenLabsLangCode}`
9070
- );
9071
- const dubbingResponse = await fetch("https://api.elevenlabs.io/v1/dubbing", {
9072
- method: "POST",
9073
- headers: {
9074
- "xi-api-key": elevenLabsApiKey
9075
- },
9076
- body: formData
9077
- });
9078
- if (!dubbingResponse.ok) {
9079
- throw await elevenLabsResponseError("ElevenLabs API error", dubbingResponse);
9157
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9158
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9159
+ try {
9160
+ const project = await client.dubbing.project.create({
9161
+ sourceUrl,
9162
+ sourceLanguage: elevenLabsSourceLangCode,
9163
+ targetLanguage: elevenLabsLangCode,
9164
+ modelId: "dubbing_v1",
9165
+ reference: `Mux Asset ${assetId} - ${elevenLabsSourceLangCode ?? "auto"} to ${elevenLabsLangCode}`
9166
+ });
9167
+ const languageId = project.languageIds?.[0];
9168
+ if (!languageId) {
9169
+ return {
9170
+ kind: "failed",
9171
+ failure: { retryable: false, detail: `ElevenLabs project ${project.projectId} returned no language target. Check the project before retrying.` }
9172
+ };
9173
+ }
9174
+ return { kind: "created", projectId: project.projectId, languageId };
9175
+ } catch (error) {
9176
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9080
9177
  }
9081
- const dubbingData = await dubbingResponse.json();
9082
- return dubbingData.dubbing_id;
9083
9178
  }
9084
9179
  async function checkElevenLabsDubbingStatus({
9085
9180
  dubbingId,
9181
+ languageId,
9086
9182
  credentials
9087
9183
  }) {
9088
9184
  "use step";
9089
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9090
- const statusResponse = await fetch(`https://api.elevenlabs.io/v1/dubbing/${dubbingId}`, {
9091
- headers: {
9092
- "xi-api-key": elevenLabsApiKey
9185
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9186
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9187
+ try {
9188
+ const [project, language] = await Promise.all([
9189
+ client.dubbing.project.get(dubbingId),
9190
+ client.dubbing.project.language.get(dubbingId, languageId)
9191
+ ]);
9192
+ return {
9193
+ kind: "status",
9194
+ status: project.status === "failed" ? "failed" : language.status,
9195
+ // A language error of `project_failed` only points at the project, so prefer the project's.
9196
+ error: project.error ?? language.error
9197
+ };
9198
+ } catch (error) {
9199
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9200
+ }
9201
+ }
9202
+ async function fetchDubbingOutput(dubbingId, languageId, output, credentials) {
9203
+ const { ElevenLabsClient } = await import("@elevenlabs/elevenlabs-js");
9204
+ const client = new ElevenLabsClient({ apiKey: await getApiKeyFromEnv("elevenlabs", credentials), maxRetries: 0 });
9205
+ for (let attempt = 0; attempt < 2; attempt++) {
9206
+ let url;
9207
+ try {
9208
+ const target = await client.dubbing.project.language.get(dubbingId, languageId);
9209
+ url = target.outputs?.[output];
9210
+ } catch (error) {
9211
+ return { kind: "failed", failure: elevenLabsSdkFailure(error) };
9212
+ }
9213
+ if (!url) {
9214
+ return {
9215
+ kind: "failed",
9216
+ failure: { reason: "output_missing", retryable: true, detail: `ElevenLabs language ${languageId} of project ${dubbingId} has no ${output} output` }
9217
+ };
9218
+ }
9219
+ let response;
9220
+ try {
9221
+ response = await fetch(url);
9222
+ } catch (error) {
9223
+ return { kind: "failed", failure: { reason: "network_error", retryable: true, detail: `Failed to fetch dubbed ${output}: ${error instanceof Error ? error.message : String(error)}` } };
9224
+ }
9225
+ if (response.ok) {
9226
+ return { kind: "fetched", response, url };
9227
+ }
9228
+ if (response.status !== 403 || attempt === 1) {
9229
+ return { kind: "failed", failure: await elevenLabsResponseFailure(response) };
9093
9230
  }
9094
- });
9095
- if (!statusResponse.ok) {
9096
- throw await elevenLabsResponseError("Status check failed", statusResponse);
9097
9231
  }
9098
- const statusData = await statusResponse.json();
9099
- return {
9100
- status: statusData.status,
9101
- targetLanguages: statusData.target_languages ?? [],
9102
- error: typeof statusData.error === "string" && statusData.error ? statusData.error : void 0
9103
- };
9232
+ return { kind: "failed", failure: { retryable: false, detail: `Failed to fetch dubbed ${output}` } };
9104
9233
  }
9105
9234
  async function downloadAndUploadDubbedAudio({
9106
9235
  dubbingId,
9107
- languageCode,
9236
+ languageId,
9108
9237
  assetId,
9109
9238
  toLanguageCode,
9110
9239
  s3Endpoint,
@@ -9115,20 +9244,32 @@ async function downloadAndUploadDubbedAudio({
9115
9244
  credentials
9116
9245
  }) {
9117
9246
  "use step";
9118
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9119
- const audioUrl = `https://api.elevenlabs.io/v1/dubbing/${dubbingId}/audio/${languageCode}`;
9120
- const audioResponse = await fetch(audioUrl, {
9121
- headers: {
9122
- "xi-api-key": elevenLabsApiKey
9123
- }
9124
- });
9125
- if (!audioResponse.ok) {
9126
- throw await elevenLabsResponseError("Failed to fetch dubbed audio", audioResponse);
9247
+ const fetched = await fetchDubbingOutput(dubbingId, languageId, "losslessAudio", credentials);
9248
+ if (fetched.kind === "failed") {
9249
+ return fetched;
9250
+ }
9251
+ const { response: audioResponse, url } = fetched;
9252
+ const mime = audioResponse.headers.get("content-type")?.split(";")[0].trim();
9253
+ const formats = {
9254
+ "audio/flac": "flac",
9255
+ "audio/x-flac": "flac",
9256
+ "audio/wav": "wav",
9257
+ "audio/x-wav": "wav",
9258
+ "audio/mp4": "m4a",
9259
+ "audio/mpeg": "mp3"
9260
+ };
9261
+ const pathExtension = new URL(url).pathname.split(".").pop()?.toLowerCase();
9262
+ const extension = (mime ? formats[mime] : void 0) ?? Object.values(formats).find((format) => format === pathExtension);
9263
+ if (!extension) {
9264
+ return {
9265
+ kind: "failed",
9266
+ failure: { reason: "unsupported_output_format", retryable: false, detail: `Unsupported dubbed audio content type: ${mime ?? "missing"}` }
9267
+ };
9127
9268
  }
9128
9269
  const dubbedAudio = new Uint8Array(await audioResponse.arrayBuffer());
9129
9270
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9130
9271
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9131
- const audioKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.m4a`;
9272
+ const audioKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.${extension}`;
9132
9273
  await putObjectWithStorageAdapter({
9133
9274
  accessKeyId: s3AccessKeyId,
9134
9275
  secretAccessKey: s3SecretAccessKey,
@@ -9137,7 +9278,7 @@ async function downloadAndUploadDubbedAudio({
9137
9278
  bucket: s3Bucket,
9138
9279
  key: audioKey,
9139
9280
  body: dubbedAudio,
9140
- contentType: "audio/mp4"
9281
+ contentType: Object.keys(formats).find((type) => formats[type] === extension)
9141
9282
  }, storageAdapter);
9142
9283
  const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9143
9284
  accessKeyId: s3AccessKeyId,
@@ -9151,11 +9292,11 @@ async function downloadAndUploadDubbedAudio({
9151
9292
  const expiryHours = Math.round((s3SignedUrlExpirySeconds ?? 86400) / 3600);
9152
9293
  console.warn(`\u2705 Audio uploaded successfully to: ${audioKey}`);
9153
9294
  console.warn(`\u{1F517} Generated presigned URL (expires in ${expiryHours} hour${expiryHours === 1 ? "" : "s"})`);
9154
- return presignedUrl;
9295
+ return { kind: "staged", presignedUrl };
9155
9296
  }
9156
9297
  async function downloadAndUploadDubTranscript({
9157
9298
  dubbingId,
9158
- languageCode,
9299
+ languageId,
9159
9300
  assetId,
9160
9301
  toLanguageCode,
9161
9302
  s3Endpoint,
@@ -9166,45 +9307,56 @@ async function downloadAndUploadDubTranscript({
9166
9307
  credentials
9167
9308
  }) {
9168
9309
  "use step";
9169
- const elevenLabsApiKey = await getApiKeyFromEnv("elevenlabs", credentials);
9170
- const transcriptUrl = `https://api.elevenlabs.io/v1/dubbing/${dubbingId}/transcripts/${languageCode}/format/webvtt`;
9171
- const transcriptResponse = await fetch(transcriptUrl, {
9172
- headers: {
9173
- "xi-api-key": elevenLabsApiKey
9174
- }
9175
- });
9176
- if (!transcriptResponse.ok) {
9177
- throw await elevenLabsResponseError("Failed to fetch dub transcript", transcriptResponse);
9310
+ try {
9311
+ const fetched = await fetchDubbingOutput(dubbingId, languageId, "subtitles", credentials);
9312
+ if (fetched.kind === "failed") {
9313
+ return fetched;
9314
+ }
9315
+ const transcriptVtt = await fetched.response.text();
9316
+ if (!transcriptVtt.trim()) {
9317
+ return { kind: "failed", failure: { retryable: false, detail: "Dub transcript response did not include webvtt content" } };
9318
+ }
9319
+ const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9320
+ const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9321
+ const vttKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.vtt`;
9322
+ await putObjectWithStorageAdapter({
9323
+ accessKeyId: s3AccessKeyId,
9324
+ secretAccessKey: s3SecretAccessKey,
9325
+ endpoint: s3Endpoint,
9326
+ region: s3Region,
9327
+ bucket: s3Bucket,
9328
+ key: vttKey,
9329
+ body: transcriptVtt,
9330
+ contentType: "text/vtt"
9331
+ }, storageAdapter);
9332
+ const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9333
+ accessKeyId: s3AccessKeyId,
9334
+ secretAccessKey: s3SecretAccessKey,
9335
+ endpoint: s3Endpoint,
9336
+ region: s3Region,
9337
+ bucket: s3Bucket,
9338
+ key: vttKey,
9339
+ expiresInSeconds: s3SignedUrlExpirySeconds ?? 86400
9340
+ }, storageAdapter);
9341
+ console.warn(`\u2705 Dub transcript uploaded successfully to: ${vttKey}`);
9342
+ return { kind: "staged", presignedUrl };
9343
+ } catch (error) {
9344
+ return { kind: "failed", failure: { retryable: true, detail: extractErrorDetail(error) } };
9178
9345
  }
9179
- const transcriptBody = await transcriptResponse.json();
9180
- const transcriptVtt = transcriptBody.webvtt;
9181
- if (!transcriptVtt) {
9182
- throw new Error("Dub transcript response did not include webvtt content");
9346
+ }
9347
+ async function attachDubbedCaptions(input) {
9348
+ "use step";
9349
+ try {
9350
+ const outcome = await replaceAndCreateTrack(input);
9351
+ if (outcome.kind === "created") {
9352
+ return { status: "created", trackId: outcome.trackId, replacedTracks: outcome.deleted };
9353
+ }
9354
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${outcome.reason}`);
9355
+ return { status: "failed", message: outcome.kind === "blocked" ? outcome.reason : CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: outcome.kind === "create_failed", replacedTracks: outcome.deleted };
9356
+ } catch (error) {
9357
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${extractErrorDetail(error)}`);
9358
+ return { status: "failed", message: CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: true, replacedTracks: [] };
9183
9359
  }
9184
- const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9185
- const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9186
- const vttKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.vtt`;
9187
- await putObjectWithStorageAdapter({
9188
- accessKeyId: s3AccessKeyId,
9189
- secretAccessKey: s3SecretAccessKey,
9190
- endpoint: s3Endpoint,
9191
- region: s3Region,
9192
- bucket: s3Bucket,
9193
- key: vttKey,
9194
- body: transcriptVtt,
9195
- contentType: "text/vtt"
9196
- }, storageAdapter);
9197
- const presignedUrl = await createPresignedGetUrlWithStorageAdapter({
9198
- accessKeyId: s3AccessKeyId,
9199
- secretAccessKey: s3SecretAccessKey,
9200
- endpoint: s3Endpoint,
9201
- region: s3Region,
9202
- bucket: s3Bucket,
9203
- key: vttKey,
9204
- expiresInSeconds: s3SignedUrlExpirySeconds ?? 86400
9205
- }, storageAdapter);
9206
- console.warn(`\u2705 Dub transcript uploaded successfully to: ${vttKey}`);
9207
- return presignedUrl;
9208
9360
  }
9209
9361
  async function translateAudio(assetId, toLanguageCode, options = {}) {
9210
9362
  "use workflow";
@@ -9220,21 +9372,26 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9220
9372
  storageAdapter,
9221
9373
  credentials: providedCredentials,
9222
9374
  replaceExistingTracks = "fail",
9375
+ captionsReplaceExistingTracks = replaceExistingTracks,
9223
9376
  trackName: providedTrackName,
9224
9377
  trackPassthrough: providedTrackPassthrough
9225
9378
  } = options;
9226
9379
  if (provider !== "elevenlabs") {
9227
9380
  throw new MuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
9228
9381
  }
9382
+ const targetLanguageCode = toISO639_1(toLanguageCode);
9383
+ if (numSpeakers !== 0) {
9384
+ throw new MuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
9385
+ }
9229
9386
  const credentials = providedCredentials;
9230
9387
  const effectiveStorageAdapter = storageAdapter;
9231
9388
  const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("translate-audio");
9232
9389
  const uploadToMux = uploadToMuxOption !== false;
9233
9390
  const uploadToS3 = uploadToS3Option || uploadToMux || uploadCaptionsToMux;
9234
- const muxLangCode = toISO639_1(toLanguageCode);
9391
+ const muxLangCode = targetLanguageCode;
9235
9392
  const trackName = providedTrackName ?? `${getLanguageName(muxLangCode) ?? muxLangCode.toUpperCase()} (Auto-dubbed)`;
9236
9393
  const audioTrackTarget = { type: "audio", languageCode: muxLangCode, name: trackName };
9237
- const captionsTrackTarget = { type: "text", languageCode: muxLangCode, name: trackName };
9394
+ const captionsTrackTarget = { type: "text", languageCode: muxLangCode, name: options.captionsTrackName ?? trackName };
9238
9395
  const s3Endpoint = options.s3Endpoint ?? env_default.S3_ENDPOINT;
9239
9396
  const s3Region = options.s3Region ?? env_default.S3_REGION ?? "auto";
9240
9397
  const s3Bucket = options.s3Bucket ?? env_default.S3_BUCKET;
@@ -9245,11 +9402,15 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9245
9402
  }
9246
9403
  const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
9247
9404
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(initialAsset);
9248
- for (const target of [
9249
- ...uploadToMux ? [audioTrackTarget] : [],
9250
- ...uploadCaptionsToMux ? [captionsTrackTarget] : []
9251
- ]) {
9252
- const plan = planTextTrackReplacement(initialAsset, target, replaceExistingTracks);
9405
+ if (isVideoOnlyAsset(initialAsset)) {
9406
+ throw new MuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
9407
+ }
9408
+ const audioTrackUnsupported = uploadToMux ? audioTrackUnsupportedReason(initialAsset) : void 0;
9409
+ if (audioTrackUnsupported) {
9410
+ throw new MuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
9411
+ }
9412
+ if (uploadToMux) {
9413
+ const plan = planTextTrackReplacement(initialAsset, audioTrackTarget, replaceExistingTracks);
9253
9414
  if (plan.kind === "blocked") {
9254
9415
  throw new MuxAiError(plan.reason, { type: "validation_error" });
9255
9416
  }
@@ -9268,11 +9429,13 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9268
9429
  }
9269
9430
  let staticRenditionCleanup = "not_created";
9270
9431
  let dubbingId;
9432
+ let languageId;
9271
9433
  let presignedUrl;
9272
9434
  let uploadedTrackId;
9273
9435
  let replacedTracks;
9274
9436
  let captionsPresignedUrl;
9275
9437
  let captionsTrackId;
9438
+ let captionsOutcome;
9276
9439
  try {
9277
9440
  let sourceRenditionName = "audio.m4a";
9278
9441
  if (isLegacyMp4SupportAsset) {
@@ -9302,75 +9465,114 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9302
9465
  audioUrl = await signUrl(audioUrl, playbackId, "video", void 0, credentials);
9303
9466
  }
9304
9467
  console.warn("\u{1F399}\uFE0F Creating dubbing job in ElevenLabs...");
9305
- const elevenLabsLangCode = toISO639_3(toLanguageCode);
9306
- const normalizedFromLanguageCode = fromLanguageCode?.trim();
9307
- const elevenLabsSourceLangCode = normalizedFromLanguageCode ? toISO639_3(normalizedFromLanguageCode) : void 0;
9468
+ const elevenLabsLangCode = toISO639_1(toBaseLanguageCode(toLanguageCode));
9469
+ const sourceLanguageCode = toISO639_1(toBaseLanguageCode(fromLanguageCode ?? "auto"));
9470
+ const elevenLabsSourceLangCode = sourceLanguageCode && sourceLanguageCode !== "auto" ? sourceLanguageCode : void 0;
9308
9471
  console.warn(
9309
9472
  `\u{1F50D} Creating dubbing job for asset ${assetId}: ${elevenLabsSourceLangCode ?? "auto"} -> ${elevenLabsLangCode}`
9310
9473
  );
9474
+ let created;
9311
9475
  try {
9312
- dubbingId = await createElevenLabsDubbingJob({
9476
+ created = await createElevenLabsDubbingJob({
9313
9477
  sourceUrl: audioUrl,
9314
9478
  assetId,
9315
9479
  elevenLabsLangCode,
9316
9480
  elevenLabsSourceLangCode,
9317
- numSpeakers,
9318
9481
  credentials
9319
9482
  });
9320
- console.warn(`\u2705 Dubbing job created with ID: ${dubbingId}`);
9321
9483
  } catch (error) {
9322
9484
  wrapError(error, "Failed to create ElevenLabs dubbing job");
9323
9485
  }
9486
+ if (created.kind === "failed") {
9487
+ const { failure } = created;
9488
+ const mayHaveCreated = failure.reason === "timeout" || failure.reason === "network_error" || failure.reason === "unexpected_response";
9489
+ console.warn(
9490
+ `Failed to create ElevenLabs dubbing project for asset ${assetId}: ${failure.detail}${mayHaveCreated ? " The project may have been created; check ElevenLabs before retrying." : ""}`
9491
+ );
9492
+ throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode });
9493
+ }
9494
+ dubbingId = created.projectId;
9495
+ languageId = created.languageId;
9496
+ console.warn(`\u2705 Dubbing job created with ID: ${dubbingId}`);
9324
9497
  console.warn("\u23F3 Waiting for dubbing to complete...");
9325
9498
  const dubbingPollTimeoutSeconds = options.dubbingPollTimeoutSeconds ?? DEFAULT_DUBBING_POLL_TIMEOUT_SECONDS;
9326
9499
  const maxPollAttempts = Math.max(1, Math.ceil(dubbingPollTimeoutSeconds * 1e3 / DUBBING_POLL_INTERVAL_MS));
9327
9500
  let dubbingStatus = "dubbing";
9328
9501
  let pollAttempts = 0;
9329
- let targetLanguages = [];
9330
9502
  let dubbingError;
9331
- while (dubbingStatus !== "dubbed" && pollAttempts < maxPollAttempts) {
9503
+ let consecutiveStatusCheckFailures = 0;
9504
+ while (dubbingStatus !== "completed" && pollAttempts < maxPollAttempts) {
9332
9505
  await sleep(DUBBING_POLL_INTERVAL_MS);
9333
9506
  pollAttempts++;
9507
+ let statusResult;
9334
9508
  try {
9335
- const statusResult = await checkElevenLabsDubbingStatus({
9509
+ statusResult = await checkElevenLabsDubbingStatus({
9336
9510
  dubbingId,
9511
+ languageId,
9337
9512
  credentials
9338
9513
  });
9339
- dubbingStatus = statusResult.status;
9340
- targetLanguages = statusResult.targetLanguages;
9341
- dubbingError = statusResult.error;
9342
9514
  } catch (error) {
9343
9515
  wrapError(error, "Failed to check dubbing status");
9344
9516
  }
9517
+ if (statusResult.kind === "failed") {
9518
+ const { failure } = statusResult;
9519
+ consecutiveStatusCheckFailures++;
9520
+ console.warn(`Status check for ElevenLabs dubbing project ${dubbingId} failed: ${failure.detail}`);
9521
+ if (!failure.retryable || consecutiveStatusCheckFailures >= MAX_CONSECUTIVE_STATUS_CHECK_FAILURES) {
9522
+ throw dubbingProviderError("Could not check audio dubbing progress.", failure);
9523
+ }
9524
+ continue;
9525
+ }
9526
+ consecutiveStatusCheckFailures = 0;
9527
+ dubbingStatus = statusResult.status;
9528
+ dubbingError = statusResult.error;
9345
9529
  if (dubbingStatus === "failed") {
9346
- console.warn(`\u274C ElevenLabs dubbing job ${dubbingId} failed: ${dubbingError ?? "no error reported"}`);
9347
- throw new MuxAiError("ElevenLabs reported that the dubbing job failed.", { type: "processing_error" });
9530
+ console.warn(`\u274C ElevenLabs dubbing project ${dubbingId} (language ${languageId}) failed: ${dubbingError ? `${dubbingError.code}: ${dubbingError.message}` : "no error reported"}`);
9531
+ if (!dubbingError) {
9532
+ throw new MuxAiError("Audio dubbing failed.", { type: "processing_error" });
9533
+ }
9534
+ throw new MuxAiError(
9535
+ `Audio dubbing failed: ${dubbingError.message}${dubbingError.retryable ? " Please try again." : ""}`,
9536
+ { type: "processing_error", retryable: dubbingError.retryable }
9537
+ );
9348
9538
  }
9349
9539
  }
9350
- if (dubbingStatus !== "dubbed") {
9540
+ if (dubbingStatus !== "completed") {
9351
9541
  throw new MuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
9352
9542
  }
9353
9543
  console.warn("\u2705 Dubbing completed successfully!");
9354
9544
  if (uploadToS3) {
9355
9545
  console.warn("\u{1F4E5} Downloading dubbed audio from ElevenLabs and staging to S3...");
9356
- const downloadLangCode = targetLanguages[0] ?? toISO639_1(toLanguageCode);
9357
- try {
9358
- presignedUrl = await downloadAndUploadDubbedAudio({
9359
- dubbingId,
9360
- languageCode: downloadLangCode,
9361
- assetId,
9362
- toLanguageCode,
9363
- s3Endpoint,
9364
- s3Region,
9365
- s3Bucket,
9366
- storageAdapter: effectiveStorageAdapter,
9367
- s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9368
- credentials
9369
- });
9370
- console.warn("\u2705 Dubbed audio staged to S3 successfully!");
9371
- } catch (error) {
9372
- wrapError(error, "Failed to download and upload dubbed audio");
9546
+ for (let attempt = 1; !presignedUrl; attempt++) {
9547
+ let staged;
9548
+ try {
9549
+ staged = await downloadAndUploadDubbedAudio({
9550
+ dubbingId,
9551
+ languageId,
9552
+ assetId,
9553
+ toLanguageCode,
9554
+ s3Endpoint,
9555
+ s3Region,
9556
+ s3Bucket,
9557
+ storageAdapter: effectiveStorageAdapter,
9558
+ s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9559
+ credentials
9560
+ });
9561
+ } catch (error) {
9562
+ wrapError(error, "Failed to download and upload dubbed audio");
9563
+ }
9564
+ if (staged.kind === "staged") {
9565
+ presignedUrl = staged.presignedUrl;
9566
+ break;
9567
+ }
9568
+ const { failure } = staged;
9569
+ console.warn(`Downloading dubbed audio for ElevenLabs dubbing project ${dubbingId} failed (attempt ${attempt}): ${failure.detail}`);
9570
+ if (!failure.retryable || attempt >= DUBBED_AUDIO_DOWNLOAD_ATTEMPTS) {
9571
+ throw dubbingProviderError("Could not download the dubbed audio.", failure);
9572
+ }
9573
+ await sleep(DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS);
9373
9574
  }
9575
+ console.warn("\u2705 Dubbed audio staged to S3 successfully!");
9374
9576
  if (uploadToMux) {
9375
9577
  console.warn("\u{1F4F9} Adding dubbed audio track to Mux asset...");
9376
9578
  let outcome;
@@ -9399,9 +9601,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9399
9601
  }
9400
9602
  try {
9401
9603
  console.warn("\u{1F4E5} Downloading dub transcript from ElevenLabs and staging to S3...");
9402
- captionsPresignedUrl = await downloadAndUploadDubTranscript({
9604
+ const transcript = await downloadAndUploadDubTranscript({
9403
9605
  dubbingId,
9404
- languageCode: downloadLangCode,
9606
+ languageId,
9405
9607
  assetId,
9406
9608
  toLanguageCode,
9407
9609
  s3Endpoint,
@@ -9411,27 +9613,36 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9411
9613
  s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds,
9412
9614
  credentials
9413
9615
  });
9414
- if (uploadCaptionsToMux) {
9616
+ if (transcript.kind === "failed") {
9617
+ captionsOutcome = { status: "unavailable", message: CAPTIONS_UNAVAILABLE_MESSAGE, retryable: transcript.failure.retryable };
9618
+ console.warn(`\u26A0\uFE0F Failed to retrieve dubbed captions: ${transcript.failure.detail}`);
9619
+ } else {
9620
+ captionsPresignedUrl = transcript.presignedUrl;
9621
+ captionsOutcome = { status: "available" };
9622
+ }
9623
+ if (uploadCaptionsToMux && captionsPresignedUrl) {
9415
9624
  console.warn("\u{1F4F9} Adding dubbed captions track to Mux asset...");
9416
- const captionsOutcome = await replaceAndCreateTrack({
9625
+ captionsOutcome = await attachDubbedCaptions({
9417
9626
  assetId,
9418
9627
  target: captionsTrackTarget,
9419
- policy: replaceExistingTracks,
9628
+ policy: captionsReplaceExistingTracks,
9420
9629
  presignedUrl: captionsPresignedUrl,
9421
9630
  passthrough: trackPassthrough,
9422
9631
  credentials
9423
9632
  });
9424
- if (captionsOutcome.deleted.length > 0) {
9425
- replacedTracks = [...replacedTracks ?? [], ...captionsOutcome.deleted];
9633
+ if (captionsOutcome.replacedTracks.length > 0) {
9634
+ replacedTracks = [...replacedTracks ?? [], ...captionsOutcome.replacedTracks];
9426
9635
  }
9427
- if (captionsOutcome.kind !== "created") {
9428
- throw new Error(captionsOutcome.reason);
9636
+ if (captionsOutcome.status === "created") {
9637
+ captionsTrackId = captionsOutcome.trackId;
9638
+ console.warn(`\u2705 Captions track added to Mux asset with ID: ${captionsTrackId}`);
9639
+ } else {
9640
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${captionsOutcome.message}`);
9429
9641
  }
9430
- captionsTrackId = captionsOutcome.trackId;
9431
- console.warn(`\u2705 Captions track added to Mux asset with ID: ${captionsTrackId}`);
9432
9642
  }
9433
9643
  } catch (error) {
9434
- console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${error instanceof Error ? error.message : "Unknown error"}`);
9644
+ captionsOutcome = captionsPresignedUrl ? { status: "failed", message: CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: true, replacedTracks: [] } : { status: "unavailable", message: CAPTIONS_UNAVAILABLE_MESSAGE, retryable: true };
9645
+ console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${extractErrorDetail(error)}`);
9435
9646
  if (captionsPresignedUrl) {
9436
9647
  console.warn("\u{1F517} You can manually add the captions track using this presigned URL:");
9437
9648
  console.warn(captionsPresignedUrl);
@@ -9450,10 +9661,10 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9450
9661
  }
9451
9662
  }
9452
9663
  }
9453
- const targetLanguage = getLanguageCodePair(toLanguageCode);
9664
+ const targetLanguage = getLanguageCodePair(targetLanguageCode);
9454
9665
  return {
9455
9666
  assetId,
9456
- targetLanguageCode: targetLanguage.iso639_1,
9667
+ targetLanguageCode,
9457
9668
  targetLanguage,
9458
9669
  dubbingId,
9459
9670
  uploadedTrackId,
@@ -9461,6 +9672,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9461
9672
  replacedTracks,
9462
9673
  captionsTrackId,
9463
9674
  captionsPresignedUrl,
9675
+ captionsOutcome,
9464
9676
  createdStaticRenditionId,
9465
9677
  staticRenditionCleanup,
9466
9678
  usage: {