| 1 |
// Load the Emscripten-generated JavaScript, which will handle the WASM binary loading. |
| 2 |
// The worker is of type "module" so that it can use ES6 module syntax. |
| 3 |
// Importantly, the emscripten code must be compiled with: -s EXPORT_ES6=1 -s MODULARIZE=1. |
| 4 |
// This allows proper module bundlers to import the worker and wasm properly with code splitting. |
| 5 |
import Module from './dcm2niix.jpeg.js'; |
| 6 |
|
| 7 |
// initialise an instance of the Emscripten Module so that |
| 8 |
// it is ready when the worker receives a message. |
| 9 |
// We keep a reference to the module so that the worker can reuse it |
| 10 |
// for all subsequent calls without having to reinitialise it (which could be slow due to the WASM loading) |
| 11 |
let mod = null |
| 12 |
Module().then((initializedMod) => { |
| 13 |
mod = initializedMod |
| 14 |
// Send a ready message once initialization is complete |
| 15 |
// so we can signal to the main thread that the worker is ready. |
| 16 |
// The Niimath.init() method will wait for this message before resolving the promise. |
| 17 |
self.postMessage({ type: 'ready' }); |
| 18 |
}) |
| 19 |
|
| 20 |
// error handler in the worker |
| 21 |
self.onerror = (message, error) => { |
| 22 |
self.postMessage({ type: 'error', message: message, error: error ? error.stack : null }); |
| 23 |
}; |
| 24 |
// unhandled promise rejection handler in the worker |
| 25 |
self.onunhandledrejection = (event) => { |
| 26 |
self.postMessage({ type: 'error', message: event.reason ? event.reason.message : 'Unhandled rejection', error: event.reason ? event.reason.stack : null }); |
| 27 |
}; |
| 28 |
|
| 29 |
// copy the files to the emscripten filesystem |
| 30 |
const copyFilesToFS = async (fileList, inDir, outDir) => { |
| 31 |
// create a directory for dcm2niix to use as its input |
| 32 |
mod.FS.mkdir(inDir); |
| 33 |
|
| 34 |
// create a directory for dcm2niix to use as its output |
| 35 |
mod.FS.mkdir(outDir); |
| 36 |
|
| 37 |
// an array to hold all the promises for copying files |
| 38 |
const promises = []; |
| 39 |
for (let fileItem of fileList) { |
| 40 |
const file = fileItem.file; |
| 41 |
// Note: Safari strips webkitRelativePath in the worker, |
| 42 |
// so we use the name property of the file object instead. |
| 43 |
const webkitRelativePath = fileItem.webkitRelativePath || file.name; |
| 44 |
const promise = new Promise((resolve, reject) => { |
| 45 |
const reader = new FileReader(); |
| 46 |
reader.onload = (e) => { |
| 47 |
try { |
| 48 |
const data = new Uint8Array(e.target.result); |
| 49 |
// webkitRelativePath has the file directory and filename separated by '/', |
| 50 |
// such as 'some_dir/some_file.dcm'. |
| 51 |
// We need to replace the '/' with '_' to create a valid name for the WASM filesystem |
| 52 |
// since some_dir does not exist at out mount point. That directory stub, |
| 53 |
// doesn't provide any useful information to dcm2niix anyway. |
| 54 |
const fileName = `${webkitRelativePath.split('/').join('_')}`; |
| 55 |
mod.FS.createDataFile(inDir, fileName, data, true, true); |
| 56 |
resolve(); // Resolve the promise when the file is successfully written |
| 57 |
} catch (error) { |
| 58 |
console.error(error); |
| 59 |
reject(error); // Reject the promise if there's an error |
| 60 |
} |
| 61 |
}; |
| 62 |
reader.onerror = () => { |
| 63 |
console.error(reader.error); |
| 64 |
reject(reader.error); // Reject the promise if there's an error reading the file |
| 65 |
}; |
| 66 |
reader.readAsArrayBuffer(file); |
| 67 |
}); |
| 68 |
|
| 69 |
promises.push(promise); |
| 70 |
} |
| 71 |
|
| 72 |
// return a promise that resolves when all files are written |
| 73 |
return Promise.all(promises); |
| 74 |
|
| 75 |
} |
| 76 |
|
| 77 |
const typeFromExtension = (fileName) => { |
| 78 |
const ext = fileName.split('.').pop(); |
| 79 |
switch (ext) { |
| 80 |
case 'nii': |
| 81 |
return 'application/sla'; |
| 82 |
case 'json': |
| 83 |
return 'application/json'; |
| 84 |
case 'txt': |
| 85 |
return 'text/plain'; |
| 86 |
case 'gz': |
| 87 |
return 'application/gzip'; |
| 88 |
case 'bvec': |
| 89 |
return 'text/plain'; |
| 90 |
case 'bval': |
| 91 |
return 'text/plain'; |
| 92 |
case 'nrrd': |
| 93 |
return 'application/octet-stream'; |
| 94 |
default: |
| 95 |
return 'application/octet-stream'; |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
const handleMessage = async (e) => { |
| 100 |
try { |
| 101 |
// name the input and output directories that will get created. |
| 102 |
const inDir = '/input'; |
| 103 |
const outDir = '/output'; |
| 104 |
const fileList = e.data.fileList; |
| 105 |
const args = e.data.cmd; |
| 106 |
// always put ['-o', outDir] at the beginning of the args array. |
| 107 |
// The user does not need to specify the output directory since it |
| 108 |
// will be a temporary directory that gets created by the worker in the emscripten filesystem. |
| 109 |
args.unshift('-o', outDir); |
| 110 |
|
| 111 |
if (!fileList || args.length < 1) { |
| 112 |
throw new Error("Expected a flat file list and at least one command"); |
| 113 |
} |
| 114 |
|
| 115 |
if (!Array.isArray(args)) { |
| 116 |
throw new Error("Expected args to be an array"); |
| 117 |
} |
| 118 |
|
| 119 |
if (!mod) { |
| 120 |
throw new Error("WASM module not loaded yet!"); |
| 121 |
} |
| 122 |
|
| 123 |
|
| 124 |
// copy the files to the emscripten filesystem |
| 125 |
await copyFilesToFS(fileList, inDir, outDir); |
| 126 |
|
| 127 |
// then add the input directory at the end of the args array |
| 128 |
args.push(inDir); |
| 129 |
// call the main function of the WASM module with the args |
| 130 |
const exitCode = mod.callMain(args); |
| 131 |
|
| 132 |
// read all files from outDir and return them |
| 133 |
const files = mod.FS.readdir(outDir); |
| 134 |
// filter out any file from the files array that starts |
| 135 |
// with a dot. FS.readdir returns '.' and '..' which is not useful. |
| 136 |
const filteredFiles = files.filter(file => !file.startsWith('.')); |
| 137 |
|
| 138 |
const convertedFiles = []; |
| 139 |
for (let file of filteredFiles) { |
| 140 |
const filePath = outDir + '/' + file; |
| 141 |
// const blob = new Blob([mod.FS.readFile(filePath)], { type: 'application/sla' }); |
| 142 |
// make a file Object from the return value of readFile |
| 143 |
const fileData = mod.FS.readFile(filePath); |
| 144 |
const f = new File([fileData], file, { type: typeFromExtension(file) }); |
| 145 |
convertedFiles.push(f); |
| 146 |
} |
| 147 |
|
| 148 |
// send a message back to the main thread with the output file, exit code and output file name |
| 149 |
self.postMessage({ convertedFiles: convertedFiles, exitCode: exitCode }); |
| 150 |
|
| 151 |
// --------- only for version test |
| 152 |
// const exitCode = mod.callMain(args); |
| 153 |
// // send a message back to the main thread with the output file, exit code and output file name |
| 154 |
// // self.postMessage({ blob: outputFile, outName: outName, exitCode: exitCode }); |
| 155 |
// self.postMessage({ blob: "blob", exitCode: exitCode }); |
| 156 |
} catch (err) { |
| 157 |
// Send error details back to the main thread |
| 158 |
self.postMessage({ type: 'error', message: err.message, error: err.stack }); |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
// Handle messages from the main thread |
| 163 |
self.addEventListener('message', handleMessage, false); |