ente/src/services/ffmpegService.ts

83 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-08-26 09:37:24 +00:00
import { createFFmpeg, FFmpeg } from '@ffmpeg/ffmpeg';
2021-08-26 12:15:18 +00:00
import { CustomError } from 'utils/common/errorUtil';
import { logError } from 'utils/sentry';
import QueueProcessor from './upload/queueProcessor';
2021-08-26 09:37:24 +00:00
import { getUint8ArrayView } from './upload/readFileService';
class FFmpegService {
private ffmpeg: FFmpeg = null;
private isLoading = null;
private generateThumbnailProcessor = new QueueProcessor<Uint8Array>(1);
2021-08-26 09:37:24 +00:00
async init() {
try {
this.ffmpeg = createFFmpeg({
2021-08-29 15:00:11 +00:00
corePath: '/js/ffmpeg/ffmpeg-core.js',
2021-08-26 09:37:24 +00:00
});
this.isLoading = this.ffmpeg.load();
await this.isLoading;
this.isLoading = null;
2021-08-26 09:37:24 +00:00
} catch (e) {
2021-08-28 13:59:00 +00:00
logError(e, 'ffmpeg load failed');
throw e;
2021-08-26 09:37:24 +00:00
}
}
async generateThumbnail(file: File) {
if (!this.ffmpeg) {
await this.init();
}
if (this.isLoading) {
await this.isLoading;
}
const response = this.generateThumbnailProcessor.queueUpRequest(
generateThumbnailHelper.bind(null, this.ffmpeg, file)
2021-08-26 09:37:24 +00:00
);
const thumbnail = await response.promise;
2021-08-26 12:15:18 +00:00
if (!thumbnail) {
throw Error(CustomError.THUMBNAIL_GENERATION_FAILED);
}
return thumbnail;
2021-08-26 09:37:24 +00:00
}
}
async function generateThumbnailHelper(ffmpeg: FFmpeg, file: File) {
2021-08-26 12:15:18 +00:00
try {
2021-08-28 16:19:31 +00:00
const inputFileName = `${Date.now().toString}-${file.name}`;
const thumbFileName = `${Date.now().toString}-thumb.png`;
2021-08-26 12:15:18 +00:00
ffmpeg.FS(
'writeFile',
2021-08-28 16:19:31 +00:00
inputFileName,
2021-08-26 12:15:18 +00:00
await getUint8ArrayView(new FileReader(), file)
);
2021-08-30 03:57:27 +00:00
let seekTime = 1.0;
let thumb = null;
while (seekTime > 0) {
try {
await ffmpeg.run(
'-i',
inputFileName,
'-ss',
`00:00:0${seekTime.toFixed(3)}`,
'-vframes',
'1',
thumbFileName
);
thumb = ffmpeg.FS('readFile', thumbFileName);
break;
} catch (e) {
2021-08-30 04:15:02 +00:00
seekTime = Number((seekTime / 10).toFixed(3));
2021-08-30 03:57:27 +00:00
}
}
2021-08-29 15:00:11 +00:00
ffmpeg.FS('unlink', thumbFileName);
2021-08-29 15:08:19 +00:00
ffmpeg.FS('unlink', inputFileName);
2021-08-26 12:15:18 +00:00
return thumb;
} catch (e) {
logError(e, 'ffmpeg thumbnail generation failed');
throw e;
}
}
2021-08-26 09:37:24 +00:00
export default new FFmpegService();