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 a `<key>={...}` Vorbis comment ending at a null byte. */
11 4 : function readVorbisCommentJson(header: string, key: string) {
12 4 : const commentStart = header.indexOf(`${key}={`)
13 4 : if (commentStart === -1) return undefined
14 3 : const jsonStart = commentStart + key.length + '='.length
15 3 : const firstClose = header.indexOf('}', jsonStart)
16 4 : if (firstClose === -1) return undefined
17 3 : const commentEnd = header.indexOf(NULL, firstClose)
18 4 : if (commentEnd === -1) return undefined
19 4 : return header.slice(jsonStart, commentEnd).match(/\{.*\}/)?.[0]
20 : }
21 :
22 2 : export async function getOggMetadata(file: File) {
23 2 : const arrayBuffer = await readFileAsArrayBuffer(file)
24 2 : if (!arrayBuffer) return { prompt: undefined, workflow: undefined }
25 : const signature = String.fromCharCode(...new Uint8Array(arrayBuffer, 0, 4))
26 2 : if (signature !== 'OggS') console.error('Invalid file signature.')
27 2 : let oggs = 0
28 2 : let header = ''
29 2 : while (header.length < arrayBuffer.byteLength) {
30 2 : const page = String.fromCharCode(
31 : ...new Uint8Array(
32 : arrayBuffer,
33 : header.length,
34 : Math.min(4096, arrayBuffer.byteLength - header.length)
35 : )
36 : )
37 2 : if (page.match('OggS\u0000')) oggs++
38 2 : header += page
39 2 : if (oggs > 1) break
40 : }
41 2 : let workflow: ComfyWorkflowJSON | undefined
42 2 : let prompt: ComfyApiWorkflow | undefined
43 2 : const prompt_s = readVorbisCommentJson(header, 'prompt')
44 2 : if (prompt_s) {
45 2 : try {
46 2 : prompt = parseJsonWithNonFinite<ComfyApiWorkflow>(prompt_s)
47 : } catch (e) {
48 0 : console.error('Failed to parse Ogg prompt metadata', e)
49 : }
50 : }
51 2 : const workflow_s = readVorbisCommentJson(header, 'workflow')
52 2 : if (workflow_s) {
53 1 : try {
54 1 : workflow = parseJsonWithNonFinite<ComfyWorkflowJSON>(workflow_s)
55 : } catch (e) {
56 0 : console.error('Failed to parse Ogg workflow metadata', e)
57 : }
58 : }
59 2 : return { prompt, workflow }
60 : }
|