Line data Source code
1 : import type {
2 : ComfyApiWorkflow,
3 : ComfyWorkflowJSON
4 : } from '@comfyorg/graph-model/workflowSchema'
5 : import { readFileAsArrayBuffer } from '@/utils/fileUtil'
6 : import { parseJsonWithNonFinite } from '@/utils/jsonUtil'
7 :
8 2356 : const NULL = '\0'
9 :
10 : /** Extracts the JSON text from an `<key>\0{...}\0` ID3 text frame. */
11 4 : function readNullTerminatedJson(header: string, key: string) {
12 4 : const frameStart = header.indexOf(`${key}${NULL}{`)
13 4 : if (frameStart === -1) return undefined
14 3 : const jsonStart = frameStart + key.length + NULL.length
15 3 : const jsonEnd = header.indexOf(`}${NULL}`, jsonStart)
16 4 : if (jsonEnd === -1) return undefined
17 3 : return header.slice(jsonStart, jsonEnd + 1)
18 : }
19 :
20 2 : export async function getMp3Metadata(file: File) {
21 2 : const arrayBuffer = await readFileAsArrayBuffer(file)
22 2 : if (!arrayBuffer) return { prompt: undefined, workflow: undefined }
23 : //https://stackoverflow.com/questions/7302439/how-can-i-determine-that-a-particular-file-is-in-fact-an-mp3-file#7302482
24 2 : const sig_bytes = new Uint8Array(arrayBuffer, 0, 3)
25 2 : if (
26 : (sig_bytes[0] != 0xff || sig_bytes[1] != 0xfb) &&
27 : (sig_bytes[0] != 0x49 || sig_bytes[1] != 0x44 || sig_bytes[2] != 0x33)
28 : )
29 0 : console.error('Invalid file signature.')
30 2 : let header = ''
31 2 : while (header.length < arrayBuffer.byteLength) {
32 2 : const page = String.fromCharCode(
33 : ...new Uint8Array(
34 : arrayBuffer,
35 : header.length,
36 : Math.min(4096, arrayBuffer.byteLength - header.length)
37 : )
38 : )
39 2 : header += page
40 2 : if (page.match('\u00ff\u00fb')) break
41 : }
42 2 : let workflow: ComfyWorkflowJSON | undefined
43 2 : let prompt: ComfyApiWorkflow | undefined
44 2 : const prompt_s = readNullTerminatedJson(header, 'prompt')
45 2 : if (prompt_s) {
46 2 : try {
47 2 : prompt = parseJsonWithNonFinite<ComfyApiWorkflow>(prompt_s)
48 : } catch (e) {
49 0 : console.error('Failed to parse MP3 prompt metadata', e)
50 : }
51 : }
52 2 : const workflow_s = readNullTerminatedJson(header, 'workflow')
53 2 : if (workflow_s) {
54 1 : try {
55 1 : workflow = parseJsonWithNonFinite<ComfyWorkflowJSON>(workflow_s)
56 : } catch (e) {
57 0 : console.error('Failed to parse MP3 workflow metadata', e)
58 : }
59 : }
60 2 : return { prompt, workflow }
61 : }
|