2023-04-09 03:35:54 +02:00
|
|
|
import { AssetEntity, AssetType, TranscodePreset } from '@app/infra/entities';
|
2023-02-25 15:12:03 +01:00
|
|
|
import { Inject, Injectable, Logger } from '@nestjs/common';
|
|
|
|
import { join } from 'path';
|
2023-03-20 16:55:28 +01:00
|
|
|
import { IAssetRepository, mapAsset, WithoutProperty } from '../asset';
|
2023-02-25 15:12:03 +01:00
|
|
|
import { CommunicationEvent, ICommunicationRepository } from '../communication';
|
2023-03-20 16:55:28 +01:00
|
|
|
import { IAssetJob, IBaseJob, IJobRepository, JobName } from '../job';
|
2023-03-25 15:50:57 +01:00
|
|
|
import { IStorageRepository, StorageCore, StorageFolder } from '../storage';
|
2023-04-04 16:48:02 +02:00
|
|
|
import { ISystemConfigRepository, SystemConfigFFmpegDto } from '../system-config';
|
|
|
|
import { SystemConfigCore } from '../system-config/system-config.core';
|
2023-04-06 05:32:59 +02:00
|
|
|
import { AudioStreamInfo, IMediaRepository, VideoStreamInfo } from './media.repository';
|
2023-02-25 15:12:03 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class MediaService {
|
|
|
|
private logger = new Logger(MediaService.name);
|
2023-03-25 15:50:57 +01:00
|
|
|
private storageCore = new StorageCore();
|
2023-04-04 16:48:02 +02:00
|
|
|
private configCore: SystemConfigCore;
|
2023-02-25 15:12:03 +01:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(IAssetRepository) private assetRepository: IAssetRepository,
|
|
|
|
@Inject(ICommunicationRepository) private communicationRepository: ICommunicationRepository,
|
|
|
|
@Inject(IJobRepository) private jobRepository: IJobRepository,
|
|
|
|
@Inject(IMediaRepository) private mediaRepository: IMediaRepository,
|
|
|
|
@Inject(IStorageRepository) private storageRepository: IStorageRepository,
|
2023-04-04 16:48:02 +02:00
|
|
|
@Inject(ISystemConfigRepository) systemConfig: ISystemConfigRepository,
|
|
|
|
) {
|
|
|
|
this.configCore = new SystemConfigCore(systemConfig);
|
|
|
|
}
|
2023-02-25 15:12:03 +01:00
|
|
|
|
2023-03-20 16:55:28 +01:00
|
|
|
async handleQueueGenerateThumbnails(job: IBaseJob): Promise<void> {
|
|
|
|
try {
|
|
|
|
const { force } = job;
|
|
|
|
|
|
|
|
const assets = force
|
|
|
|
? await this.assetRepository.getAll()
|
|
|
|
: await this.assetRepository.getWithout(WithoutProperty.THUMBNAIL);
|
|
|
|
|
|
|
|
for (const asset of assets) {
|
|
|
|
await this.jobRepository.queue({ name: JobName.GENERATE_JPEG_THUMBNAIL, data: { asset } });
|
|
|
|
}
|
|
|
|
} catch (error: any) {
|
|
|
|
this.logger.error('Failed to queue generate thumbnail jobs', error.stack);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-25 15:12:03 +01:00
|
|
|
async handleGenerateJpegThumbnail(data: IAssetJob): Promise<void> {
|
|
|
|
const { asset } = data;
|
|
|
|
|
2023-03-24 03:40:46 +01:00
|
|
|
try {
|
2023-03-25 15:50:57 +01:00
|
|
|
const resizePath = this.storageCore.getFolderLocation(StorageFolder.THUMBNAILS, asset.ownerId);
|
2023-03-24 03:40:46 +01:00
|
|
|
this.storageRepository.mkdirSync(resizePath);
|
2023-03-25 15:50:57 +01:00
|
|
|
const jpegThumbnailPath = join(resizePath, `${asset.id}.jpeg`);
|
2023-03-24 03:40:46 +01:00
|
|
|
|
2023-04-04 03:18:27 +02:00
|
|
|
const thumbnailDimension = 1440;
|
2023-03-24 03:40:46 +01:00
|
|
|
if (asset.type == AssetType.IMAGE) {
|
|
|
|
try {
|
2023-04-04 03:18:27 +02:00
|
|
|
await this.mediaRepository.resize(asset.originalPath, jpegThumbnailPath, {
|
|
|
|
size: thumbnailDimension,
|
|
|
|
format: 'jpeg',
|
|
|
|
});
|
2023-03-24 03:40:46 +01:00
|
|
|
} catch (error) {
|
|
|
|
this.logger.warn(
|
|
|
|
`Failed to generate jpeg thumbnail using sharp, trying with exiftool-vendored (asset=${asset.id})`,
|
|
|
|
);
|
|
|
|
await this.mediaRepository.extractThumbnailFromExif(asset.originalPath, jpegThumbnailPath);
|
|
|
|
}
|
2023-02-25 15:12:03 +01:00
|
|
|
}
|
|
|
|
|
2023-03-24 03:40:46 +01:00
|
|
|
if (asset.type == AssetType.VIDEO) {
|
|
|
|
this.logger.log('Start Generating Video Thumbnail');
|
2023-04-04 03:18:27 +02:00
|
|
|
await this.mediaRepository.extractVideoThumbnail(asset.originalPath, jpegThumbnailPath, thumbnailDimension);
|
2023-03-24 03:40:46 +01:00
|
|
|
this.logger.log(`Generating Video Thumbnail Success ${asset.id}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.assetRepository.save({ id: asset.id, resizePath: jpegThumbnailPath });
|
|
|
|
|
2023-02-25 15:12:03 +01:00
|
|
|
asset.resizePath = jpegThumbnailPath;
|
|
|
|
|
|
|
|
await this.jobRepository.queue({ name: JobName.GENERATE_WEBP_THUMBNAIL, data: { asset } });
|
2023-03-20 16:55:28 +01:00
|
|
|
await this.jobRepository.queue({ name: JobName.CLASSIFY_IMAGE, data: { asset } });
|
|
|
|
await this.jobRepository.queue({ name: JobName.DETECT_OBJECTS, data: { asset } });
|
2023-03-18 14:44:42 +01:00
|
|
|
await this.jobRepository.queue({ name: JobName.ENCODE_CLIP, data: { asset } });
|
2023-02-25 15:12:03 +01:00
|
|
|
|
|
|
|
this.communicationRepository.send(CommunicationEvent.UPLOAD_SUCCESS, asset.ownerId, mapAsset(asset));
|
2023-03-24 03:40:46 +01:00
|
|
|
} catch (error: any) {
|
|
|
|
this.logger.error(`Failed to generate thumbnail for asset: ${asset.id}/${asset.type}`, error.stack);
|
2023-02-25 15:12:03 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleGenerateWepbThumbnail(data: IAssetJob): Promise<void> {
|
|
|
|
const { asset } = data;
|
|
|
|
|
|
|
|
if (!asset.resizePath) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const webpPath = asset.resizePath.replace('jpeg', 'webp');
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.mediaRepository.resize(asset.resizePath, webpPath, { size: 250, format: 'webp' });
|
|
|
|
await this.assetRepository.save({ id: asset.id, webpPath: webpPath });
|
|
|
|
} catch (error: any) {
|
2023-04-04 16:48:02 +02:00
|
|
|
this.logger.error(`Failed to generate webp thumbnail for asset: ${asset.id}`, error.stack);
|
2023-02-25 15:12:03 +01:00
|
|
|
}
|
|
|
|
}
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
async handleQueueVideoConversion(job: IBaseJob) {
|
|
|
|
const { force } = job;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const assets = force
|
|
|
|
? await this.assetRepository.getAll({ type: AssetType.VIDEO })
|
|
|
|
: await this.assetRepository.getWithout(WithoutProperty.ENCODED_VIDEO);
|
|
|
|
for (const asset of assets) {
|
|
|
|
await this.jobRepository.queue({ name: JobName.VIDEO_CONVERSION, data: { asset } });
|
|
|
|
}
|
|
|
|
} catch (error: any) {
|
|
|
|
this.logger.error('Failed to queue video conversions', error.stack);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async handleVideoConversion(job: IAssetJob) {
|
2023-04-11 15:56:52 +02:00
|
|
|
const [asset] = await this.assetRepository.getByIds([job.asset.id]);
|
|
|
|
|
|
|
|
if (!asset) {
|
|
|
|
return;
|
|
|
|
}
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
const input = asset.originalPath;
|
|
|
|
const outputFolder = this.storageCore.getFolderLocation(StorageFolder.ENCODED_VIDEO, asset.ownerId);
|
|
|
|
const output = join(outputFolder, `${asset.id}.mp4`);
|
|
|
|
this.storageRepository.mkdirSync(outputFolder);
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
const { videoStreams, audioStreams, format } = await this.mediaRepository.probe(input);
|
|
|
|
const mainVideoStream = this.getMainVideoStream(videoStreams);
|
|
|
|
const mainAudioStream = this.getMainAudioStream(audioStreams);
|
|
|
|
const containerExtension = format.formatName;
|
|
|
|
if (!mainVideoStream || !mainAudioStream || !containerExtension) {
|
2023-04-04 16:48:02 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const { ffmpeg: config } = await this.configCore.getConfig();
|
|
|
|
|
2023-04-09 03:35:54 +02:00
|
|
|
const required = this.isTranscodeRequired(asset, mainVideoStream, mainAudioStream, containerExtension, config);
|
2023-04-04 16:48:02 +02:00
|
|
|
if (!required) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
const options = this.getFfmpegOptions(mainVideoStream, config);
|
|
|
|
|
|
|
|
this.logger.log(`Start encoding video ${asset.id} ${options}`);
|
2023-04-04 16:48:02 +02:00
|
|
|
await this.mediaRepository.transcode(input, output, options);
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
this.logger.log(`Encoding success ${asset.id}`);
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
await this.assetRepository.save({ id: asset.id, encodedVideoPath: output });
|
|
|
|
} catch (error: any) {
|
|
|
|
this.logger.error(`Failed to handle video conversion for asset: ${asset.id}`, error.stack);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
private getMainVideoStream(streams: VideoStreamInfo[]): VideoStreamInfo | null {
|
|
|
|
return streams.sort((stream1, stream2) => stream2.frameCount - stream1.frameCount)[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
private getMainAudioStream(streams: AudioStreamInfo[]): AudioStreamInfo | null {
|
|
|
|
return streams[0];
|
2023-04-04 16:48:02 +02:00
|
|
|
}
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
private isTranscodeRequired(
|
2023-04-09 03:35:54 +02:00
|
|
|
asset: AssetEntity,
|
2023-04-06 05:32:59 +02:00
|
|
|
videoStream: VideoStreamInfo,
|
|
|
|
audioStream: AudioStreamInfo,
|
|
|
|
containerExtension: string,
|
|
|
|
ffmpegConfig: SystemConfigFFmpegDto,
|
|
|
|
): boolean {
|
|
|
|
if (!videoStream.height || !videoStream.width) {
|
2023-04-04 16:48:02 +02:00
|
|
|
this.logger.error('Skipping transcode, height or width undefined for video stream');
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2023-04-06 05:32:59 +02:00
|
|
|
const isTargetVideoCodec = videoStream.codecName === ffmpegConfig.targetVideoCodec;
|
|
|
|
const isTargetAudioCodec = audioStream.codecName === ffmpegConfig.targetAudioCodec;
|
|
|
|
const isTargetContainer = ['mov,mp4,m4a,3gp,3g2,mj2', 'mp4', 'mov'].includes(containerExtension);
|
|
|
|
|
2023-04-09 03:35:54 +02:00
|
|
|
this.logger.verbose(
|
|
|
|
`${asset.id}: AudioCodecName ${audioStream.codecName}, AudioStreamCodecType ${audioStream.codecType}, containerExtension ${containerExtension}`,
|
|
|
|
);
|
2023-04-06 05:32:59 +02:00
|
|
|
|
|
|
|
const allTargetsMatching = isTargetVideoCodec && isTargetAudioCodec && isTargetContainer;
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
const targetResolution = Number.parseInt(ffmpegConfig.targetResolution);
|
2023-04-06 05:32:59 +02:00
|
|
|
const isLargerThanTargetResolution = Math.min(videoStream.height, videoStream.width) > targetResolution;
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
switch (ffmpegConfig.transcode) {
|
2023-04-06 05:32:59 +02:00
|
|
|
case TranscodePreset.DISABLED:
|
|
|
|
return false;
|
|
|
|
|
2023-04-04 16:48:02 +02:00
|
|
|
case TranscodePreset.ALL:
|
|
|
|
return true;
|
|
|
|
|
|
|
|
case TranscodePreset.REQUIRED:
|
2023-04-06 05:32:59 +02:00
|
|
|
return !allTargetsMatching;
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
case TranscodePreset.OPTIMAL:
|
2023-04-06 05:32:59 +02:00
|
|
|
return !allTargetsMatching || isLargerThanTargetResolution;
|
2023-04-04 16:48:02 +02:00
|
|
|
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private getFfmpegOptions(stream: VideoStreamInfo, ffmpeg: SystemConfigFFmpegDto) {
|
|
|
|
const options = [
|
|
|
|
`-crf ${ffmpeg.crf}`,
|
|
|
|
`-preset ${ffmpeg.preset}`,
|
|
|
|
`-vcodec ${ffmpeg.targetVideoCodec}`,
|
|
|
|
`-acodec ${ffmpeg.targetAudioCodec}`,
|
|
|
|
// Makes a second pass moving the moov atom to the beginning of
|
|
|
|
// the file for improved playback speed.
|
|
|
|
`-movflags faststart`,
|
|
|
|
];
|
|
|
|
|
|
|
|
const videoIsRotated = Math.abs(stream.rotation) === 90;
|
|
|
|
const targetResolution = Number.parseInt(ffmpeg.targetResolution);
|
|
|
|
|
|
|
|
const isVideoVertical = stream.height > stream.width || videoIsRotated;
|
|
|
|
const scaling = isVideoVertical ? `${targetResolution}:-2` : `-2:${targetResolution}`;
|
|
|
|
|
|
|
|
const shouldScale = Math.min(stream.height, stream.width) > targetResolution;
|
|
|
|
if (shouldScale) {
|
|
|
|
options.push(`-vf scale=${scaling}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return options;
|
|
|
|
}
|
2023-02-25 15:12:03 +01:00
|
|
|
}
|