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';
|
2021-08-26 11:01:33 +00:00
|
|
|
import QueueProcessor from './upload/queueProcessor';
|
2021-08-26 09:37:24 +00:00
|
|
|
import { getUint8ArrayView } from './upload/readFileService';
|
|
|
|
|
|
|
|
class FFmpegService {
|
|
|
|
private ffmpeg: FFmpeg = null;
|
2021-08-26 11:01:33 +00:00
|
|
|
private isLoading = null;
|
|
|
|
|
|
|
|
private generateThumbnailProcessor = new QueueProcessor<Uint8Array>(1);
|
2021-08-26 09:37:24 +00:00
|
|
|
async init() {
|
|
|
|
try {
|
|
|
|
this.ffmpeg = createFFmpeg({
|
|
|
|
log: true,
|
|
|
|
corePath: '/js/ffmpeg-core.js',
|
|
|
|
});
|
|
|
|
console.log('Loading ffmpeg-core.js');
|
2021-08-26 11:01:33 +00:00
|
|
|
this.isLoading = this.ffmpeg.load();
|
|
|
|
await this.isLoading;
|
|
|
|
this.isLoading = null;
|
|
|
|
console.log('ffmpeg loaded');
|
2021-08-26 09:37:24 +00:00
|
|
|
} catch (e) {
|
|
|
|
throw Error('ffmpeg load failed');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async generateThumbnail(file: File) {
|
|
|
|
if (!this.ffmpeg) {
|
|
|
|
await this.init();
|
|
|
|
}
|
2021-08-26 11:01:33 +00:00
|
|
|
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
|
|
|
);
|
|
|
|
|
2021-08-26 11:01:33 +00:00
|
|
|
const thumbnail = await response.promise;
|
2021-08-26 12:15:18 +00:00
|
|
|
if (!thumbnail) {
|
|
|
|
throw Error(CustomError.THUMBNAIL_GENERATION_FAILED);
|
|
|
|
}
|
2021-08-26 11:01:33 +00:00
|
|
|
return thumbnail;
|
2021-08-26 09:37:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-26 11:01:33 +00:00
|
|
|
async function generateThumbnailHelper(ffmpeg: FFmpeg, file: File) {
|
2021-08-26 12:15:18 +00:00
|
|
|
try {
|
|
|
|
ffmpeg.FS(
|
|
|
|
'writeFile',
|
|
|
|
file.name,
|
|
|
|
await getUint8ArrayView(new FileReader(), file)
|
|
|
|
);
|
2021-08-26 11:01:33 +00:00
|
|
|
|
2021-08-26 12:15:18 +00:00
|
|
|
await ffmpeg.run(
|
|
|
|
'-i',
|
|
|
|
file.name,
|
|
|
|
'-ss',
|
|
|
|
'00:00:01.000',
|
|
|
|
'-vframes',
|
|
|
|
'1',
|
|
|
|
'thumb.png'
|
|
|
|
);
|
|
|
|
console.log('Complete transcoding');
|
|
|
|
const thumb = ffmpeg.FS('readFile', 'thumb.png');
|
|
|
|
return thumb;
|
|
|
|
} catch (e) {
|
|
|
|
console.log(e);
|
|
|
|
logError(e, 'ffmpeg thumbnail generation failed');
|
|
|
|
throw e;
|
|
|
|
}
|
2021-08-26 11:01:33 +00:00
|
|
|
}
|
|
|
|
|
2021-08-26 09:37:24 +00:00
|
|
|
export default new FFmpegService();
|