Open History to see the last commit
1/**
2 * Coerce the various audio input shapes accepted by `TranscriptionOptions.audio`
3 * into a `File` suitable for `multipart/form-data` uploads.
4 *
5 * For base64 string inputs we require an explicit MIME type — either via a
6 * `data:<mime>;base64,<payload>` URI prefix, or via the caller-provided
7 * `audioFormat` parameter. Bare base64 without either is rejected, because
8 * silently defaulting to `audio/mpeg` misreports non-mp3 audio to the server.
9 *
10 * The same rule applies to raw `ArrayBuffer` inputs: the caller must supply
11 * an `audioFormat` so we know what MIME type and extension to use.
12 */
13export function toAudioFile(
14 audio: string | File | Blob | ArrayBuffer,
15 audioFormat?: string,
16): File {
17 if (typeof File !== 'undefined' && audio instanceof File) {
18 // Prefer the caller-supplied `audioFormat` over a potentially empty or
19 // incorrect `File.type` — callers pass `audioFormat` precisely because
20 // they have more context than the browser does about the payload. If
21 // neither is set, fall through to the Blob-style error path below.
22 if (audioFormat) {
23 const mimeType = toMimeType(audioFormat)
24 return new File([audio], `audio.${extensionFor(mimeType)}`, {
25 type: mimeType,
26 })
27 }
28 if (audio.type) {
29 return audio
30 }
31 throw new Error(
32 'toAudioFile cannot infer type for File input with empty .type — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
33 )
34 }
35
36 if (typeof Blob !== 'undefined' && audio instanceof Blob) {
37 // Mirror the ArrayBuffer / bare-base64 paths: prefer the explicit
38 // audioFormat argument over the Blob's (often empty) .type. We refuse to
39 // fall back to `application/octet-stream` because that mislabels audio
40 // for the server.
41 const mimeType = audioFormat
42 ? toMimeType(audioFormat)
43 : audio.type || undefined
44 if (!mimeType) {
45 throw new Error(
46 'toAudioFile cannot infer type for Blob input with empty .type — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
47 )
48 }
49 return new File([audio], `audio.${extensionFor(mimeType)}`, {
50 type: mimeType,
51 })
52 }
53
54 if (audio instanceof ArrayBuffer) {
55 if (!audioFormat) {
56 throw new Error(
57 'toAudioFile cannot infer type for ArrayBuffer input — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
58 )
59 }
60 const mimeType = toMimeType(audioFormat)
61 return new File([audio], `audio.${extensionFor(mimeType)}`, {
62 type: mimeType,
63 })
64 }
65
66 if (typeof audio === 'string') {
67 if (audio.startsWith('data:')) {
68 const [header, base64Data] = audio.split(',')
69 // Fail loudly on malformed data: URIs instead of silently defaulting
70 // to `audio/mpeg` — the file's contract is that we never mislabel
71 // audio for the server.
72 const headerMatch = header?.match(/data:([^;]+)/)
73 const uriMimeType = headerMatch?.[1]
74 if (!uriMimeType) {
75 throw new Error(
76 'Malformed data: URI in toAudioFile: cannot parse MIME type — expected data:<mime>[;charset=…][;base64],<payload>',
77 )
78 }
79 if (base64Data === undefined || base64Data.trim() === '') {
80 throw new Error(
81 'Malformed data: URI in toAudioFile: missing base64 payload after comma',
82 )
83 }
84 // Caller-supplied `audioFormat` wins over the URI-embedded MIME: the
85 // caller has more context (the URI MIME may be wrong, or a generic
86 // `application/octet-stream`).
87 const mimeType = audioFormat ? toMimeType(audioFormat) : uriMimeType
88 const buffer = base64ToArrayBuffer(base64Data)
89 return new File([buffer], `audio.${extensionFor(mimeType)}`, {
90 type: mimeType,
91 })
92 }
93
94 if (!audioFormat) {
95 throw new Error(
96 'toAudioFile requires a data: URI (e.g. data:audio/wav;base64,...) or an explicit audioFormat argument — bare base64 strings have no MIME type to infer',
97 )
98 }
99
100 const buffer = base64ToArrayBuffer(audio)
101 const mimeType = toMimeType(audioFormat)
102 return new File([buffer], `audio.${extensionFor(mimeType)}`, {
103 type: mimeType,
104 })
105 }
106
107 throw new Error('Invalid audio input type')
108}
109
110function toMimeType(audioFormat: string): string {
111 // Accept either "audio/…" strings or bare extensions like "mp3".
112 if (audioFormat.includes('/')) return audioFormat
113 const ext = audioFormat.toLowerCase()
114 switch (ext) {
115 case 'mp3':
116 return 'audio/mpeg'
117 case 'wav':
118 return 'audio/wav'
119 case 'ogg':
120 return 'audio/ogg'
121 case 'opus':
122 return 'audio/opus'
123 case 'flac':
124 return 'audio/flac'
125 case 'aac':
126 return 'audio/aac'
127 case 'mp4':
128 return 'audio/mp4'
129 case 'm4a':
130 return 'audio/mp4'
131 case 'webm':
132 return 'audio/webm'
133 case 'pcm':
134 return 'audio/L16'
135 case 'mulaw':
136 return 'audio/basic'
137 case 'alaw':
138 return 'audio/x-alaw-basic'
139 default:
140 return `audio/${ext}`
141 }
142}
143
144function extensionFor(mimeType: string): string {
145 switch (mimeType) {
146 case 'audio/mpeg':
147 return 'mp3'
148 case 'audio/wav':
149 case 'audio/x-wav':
150 return 'wav'
151 case 'audio/ogg':
152 return 'ogg'
153 case 'audio/opus':
154 return 'opus'
155 case 'audio/flac':
156 return 'flac'
157 case 'audio/aac':
158 return 'aac'
159 case 'audio/mp4':
160 return 'm4a'
161 case 'audio/webm':
162 return 'webm'
163 case 'audio/L16':
164 return 'pcm'
165 case 'audio/basic':
166 return 'mulaw'
167 case 'audio/x-alaw-basic':
168 return 'alaw'
169 default: {
170 const slash = mimeType.indexOf('/')
171 if (slash === -1) return 'bin'
172 return mimeType.slice(slash + 1) || 'bin'
173 }
174 }
175}
176
177/**
178 * Cross-runtime ArrayBuffer → base64 conversion.
179 *
180 * Uses Node's `Buffer` when available (fastest path on server) and falls
181 * back to `btoa` + chunked `String.fromCharCode` everywhere else (browser,
182 * Cloudflare Workers, Bun, Deno). Chunking is required because a very
183 * large audio buffer spread into `String.fromCharCode(...bytes)` in one
184 * call can hit `Maximum call stack size exceeded`.
185 */
186export function arrayBufferToBase64(buffer: ArrayBuffer): string {
187 if (typeof Buffer !== 'undefined') {
188 return Buffer.from(buffer).toString('base64')
189 }
190 const bytes = new Uint8Array(buffer)
191 const chunkSize = 0x8000
192 let binary = ''
193 for (let i = 0; i < bytes.length; i += chunkSize) {
194 const end = Math.min(i + chunkSize, bytes.length)
195 binary += String.fromCharCode.apply(
196 null,
197 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- TS lib types String.fromCharCode.apply as Array<number> but runtime accepts any ArrayLike
198 bytes.subarray(i, end) as unknown as Array<number>,
199 )
200 }
201 return btoa(binary)
202}
203
204function base64ToArrayBuffer(base64: string): ArrayBuffer {
205 let binary: string
206 try {
207 binary = atob(base64)
208 } catch (err) {
209 const msg = err instanceof Error ? err.message : String(err)
210 throw new Error(`Invalid base64 input to toAudioFile: ${msg}`)
211 }
212 const buffer = new ArrayBuffer(binary.length)
213 const bytes = new Uint8Array(buffer)
214 for (let i = 0; i < binary.length; i++) {
215 bytes[i] = binary.charCodeAt(i)
216 }
217 return buffer
218}