Refactor remote script loading code
This commit is contained in:
@@ -1,23 +1,50 @@
|
||||
/* eslint-disable no-undef */
|
||||
const resolveURL = require('resolve-url');
|
||||
const { log } = require('../utils/log');
|
||||
|
||||
/*
|
||||
* Fetch data from remote URL and convert to blob URL
|
||||
* to avoid CORS issue
|
||||
*/
|
||||
const toBlobURL = async (url, mimeType) => {
|
||||
log('info', `fetch ${url}`);
|
||||
const buf = await (await fetch(url)).arrayBuffer();
|
||||
log('info', `${url} file size = ${buf.byteLength} bytes`);
|
||||
const blob = new Blob([buf], { type: mimeType });
|
||||
const blobURL = URL.createObjectURL(blob);
|
||||
log('info', `${url} blob URL = ${blobURL}`);
|
||||
return blobURL;
|
||||
};
|
||||
|
||||
module.exports = async ({ corePath: _corePath }) => {
|
||||
if (typeof _corePath !== 'string') {
|
||||
throw Error('corePath should be a string!');
|
||||
}
|
||||
if (typeof window.createFFmpegCore === 'undefined') {
|
||||
log('info', 'fetch ffmpeg-core.worker.js script');
|
||||
const corePath = resolveURL(_corePath);
|
||||
const workerBlob = await (await fetch(corePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'))).blob();
|
||||
window.FFMPEG_CORE_WORKER_SCRIPT = URL.createObjectURL(workerBlob);
|
||||
log('info', `worker object URL=${window.FFMPEG_CORE_WORKER_SCRIPT}`);
|
||||
log('info', `download ffmpeg-core script (~25 MB) from ${corePath}`);
|
||||
const coreRemotePath = resolveURL(_corePath);
|
||||
const corePath = await toBlobURL(
|
||||
coreRemotePath,
|
||||
'application/javascript',
|
||||
);
|
||||
const wasmPath = await toBlobURL(
|
||||
coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.wasm'),
|
||||
'application/wasm',
|
||||
);
|
||||
const workerPath = await toBlobURL(
|
||||
coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'),
|
||||
'application/javascript',
|
||||
);
|
||||
if (typeof createFFmpegCore === 'undefined') {
|
||||
return new Promise((resolve) => {
|
||||
const script = document.createElement('script');
|
||||
const eventHandler = () => {
|
||||
script.removeEventListener('load', eventHandler);
|
||||
log('info', 'initialize ffmpeg-core');
|
||||
resolve(window.createFFmpegCore);
|
||||
log('info', 'ffmpeg-core.js script loaded');
|
||||
resolve({
|
||||
createFFmpegCore,
|
||||
corePath,
|
||||
wasmPath,
|
||||
workerPath,
|
||||
});
|
||||
};
|
||||
script.src = corePath;
|
||||
script.type = 'text/javascript';
|
||||
@@ -25,6 +52,11 @@ module.exports = async ({ corePath: _corePath }) => {
|
||||
document.getElementsByTagName('head')[0].appendChild(script);
|
||||
});
|
||||
}
|
||||
log('info', 'ffmpeg-core is loaded already');
|
||||
return Promise.resolve(window.createFFmpegCore);
|
||||
log('info', 'ffmpeg-core.js script is loaded already');
|
||||
return Promise.resolve({
|
||||
createFFmpegCore,
|
||||
corePath,
|
||||
wasmPath,
|
||||
workerPath,
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user