1 import { Job } from 'bullmq'
2 import { move, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { getFFmpegCommandWrapperOptions } from '@server/helpers/ffmpeg'
5 import { createTorrentAndSetInfoHashFromPath } from '@server/helpers/webtorrent'
6 import { CONFIG } from '@server/initializers/config'
7 import { VIDEO_FILTERS } from '@server/initializers/constants'
8 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
9 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
10 import { createOptimizeOrMergeAudioJobs } from '@server/lib/transcoding/create-transcoding-job'
11 import { VideoTranscodingProfilesManager } from '@server/lib/transcoding/default-transcoding-profiles'
12 import { isAbleToUploadVideo } from '@server/lib/user'
13 import { buildFileMetadata, removeHLSPlaylist, removeWebTorrentFile } from '@server/lib/video-file'
14 import { VideoPathManager } from '@server/lib/video-path-manager'
15 import { approximateIntroOutroAdditionalSize } from '@server/lib/video-studio'
16 import { UserModel } from '@server/models/user/user'
17 import { VideoModel } from '@server/models/video/video'
18 import { VideoFileModel } from '@server/models/video/video-file'
19 import { MVideo, MVideoFile, MVideoFullLight, MVideoId, MVideoWithAllFiles } from '@server/types/models'
20 import { getLowercaseExtension, pick } from '@shared/core-utils'
21 import { buildUUID, getFileSize } from '@shared/extra-utils'
22 import { FFmpegEdition, ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamDuration, getVideoStreamFPS } from '@shared/ffmpeg'
24 VideoStudioEditionPayload,
26 VideoStudioTaskCutPayload,
27 VideoStudioTaskIntroPayload,
28 VideoStudioTaskOutroPayload,
29 VideoStudioTaskPayload,
30 VideoStudioTaskWatermarkPayload
31 } from '@shared/models'
32 import { logger, loggerTagsFactory } from '../../../helpers/logger'
34 const lTagsBase = loggerTagsFactory('video-edition')
36 async function processVideoStudioEdition (job: Job) {
37 const payload = job.data as VideoStudioEditionPayload
38 const lTags = lTagsBase(payload.videoUUID)
40 logger.info('Process video studio edition of %s in job %s.', payload.videoUUID, job.id, lTags)
42 const video = await VideoModel.loadFull(payload.videoUUID)
44 // No video, maybe deleted?
46 logger.info('Can\'t process job %d, video does not exist.', job.id, lTags)
50 await checkUserQuotaOrThrow(video, payload)
52 const inputFile = video.getMaxQualityFile()
54 const editionResultPath = await VideoPathManager.Instance.makeAvailableVideoFile(inputFile, async originalFilePath => {
55 let tmpInputFilePath: string
56 let outputPath: string
58 for (const task of payload.tasks) {
59 const outputFilename = buildUUID() + inputFile.extname
60 outputPath = join(CONFIG.STORAGE.TMP_DIR, outputFilename)
63 inputPath: tmpInputFilePath ?? originalFilePath,
70 if (tmpInputFilePath) await remove(tmpInputFilePath)
72 // For the next iteration
73 tmpInputFilePath = outputPath
79 logger.info('Video edition ended for video %s.', video.uuid, lTags)
81 const newFile = await buildNewFile(video, editionResultPath)
83 const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newFile)
84 await move(editionResultPath, outputPath)
86 await createTorrentAndSetInfoHashFromPath(video, newFile, outputPath)
87 await removeAllFiles(video, newFile)
91 video.duration = await getVideoStreamDuration(outputPath)
94 await federateVideoIfNeeded(video, false, undefined)
96 const user = await UserModel.loadByVideoId(video.id)
98 await createOptimizeOrMergeAudioJobs({ video, videoFile: newFile, isNewVideo: false, user, videoFileAlreadyLocked: false })
101 // ---------------------------------------------------------------------------
104 processVideoStudioEdition
107 // ---------------------------------------------------------------------------
109 type TaskProcessorOptions <T extends VideoStudioTaskPayload = VideoStudioTaskPayload> = {
114 lTags: { tags: string[] }
117 const taskProcessors: { [id in VideoStudioTask['name']]: (options: TaskProcessorOptions) => Promise<any> } = {
118 'add-intro': processAddIntroOutro,
119 'add-outro': processAddIntroOutro,
121 'add-watermark': processAddWatermark
124 async function processTask (options: TaskProcessorOptions) {
125 const { video, task, lTags } = options
127 logger.info('Processing %s task for video %s.', task.name, video.uuid, { task, ...lTags })
129 const processor = taskProcessors[options.task.name]
130 if (!process) throw new Error('Unknown task ' + task.name)
132 return processor(options)
135 function processAddIntroOutro (options: TaskProcessorOptions<VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload>) {
136 const { task, lTags } = options
138 logger.debug('Will add intro/outro to the video.', { options, ...lTags })
140 return buildFFmpegEdition().addIntroOutro({
141 ...pick(options, [ 'inputPath', 'outputPath' ]),
143 introOutroPath: task.options.file,
144 type: task.name === 'add-intro'
150 function processCut (options: TaskProcessorOptions<VideoStudioTaskCutPayload>) {
151 const { task, lTags } = options
153 logger.debug('Will cut the video.', { options, ...lTags })
155 return buildFFmpegEdition().cutVideo({
156 ...pick(options, [ 'inputPath', 'outputPath' ]),
158 start: task.options.start,
159 end: task.options.end
163 function processAddWatermark (options: TaskProcessorOptions<VideoStudioTaskWatermarkPayload>) {
164 const { task, lTags } = options
166 logger.debug('Will add watermark to the video.', { options, ...lTags })
168 return buildFFmpegEdition().addWatermark({
169 ...pick(options, [ 'inputPath', 'outputPath' ]),
171 watermarkPath: task.options.file,
174 watermarkSizeRatio: VIDEO_FILTERS.WATERMARK.SIZE_RATIO,
175 horitonzalMarginRatio: VIDEO_FILTERS.WATERMARK.HORIZONTAL_MARGIN_RATIO,
176 verticalMarginRatio: VIDEO_FILTERS.WATERMARK.VERTICAL_MARGIN_RATIO
181 // ---------------------------------------------------------------------------
183 async function buildNewFile (video: MVideoId, path: string) {
184 const videoFile = new VideoFileModel({
185 extname: getLowercaseExtension(path),
186 size: await getFileSize(path),
187 metadata: await buildFileMetadata(path),
188 videoStreamingPlaylistId: null,
192 const probe = await ffprobePromise(path)
194 videoFile.fps = await getVideoStreamFPS(path, probe)
195 videoFile.resolution = (await getVideoStreamDimensionsInfo(path, probe)).resolution
197 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
202 async function removeAllFiles (video: MVideoWithAllFiles, webTorrentFileException: MVideoFile) {
203 await removeHLSPlaylist(video)
205 for (const file of video.VideoFiles) {
206 if (file.id === webTorrentFileException.id) continue
208 await removeWebTorrentFile(video, file.id)
212 async function checkUserQuotaOrThrow (video: MVideoFullLight, payload: VideoStudioEditionPayload) {
213 const user = await UserModel.loadByVideoId(video.id)
215 const filePathFinder = (i: number) => (payload.tasks[i] as VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload).options.file
217 const additionalBytes = await approximateIntroOutroAdditionalSize(video, payload.tasks, filePathFinder)
218 if (await isAbleToUploadVideo(user.id, additionalBytes) === false) {
219 throw new Error('Quota exceeded for this user to edit the video')
223 function buildFFmpegEdition () {
224 return new FFmpegEdition(getFFmpegCommandWrapperOptions('vod', VideoTranscodingProfilesManager.Instance.getAvailableEncoders()))