1 import { Job } from 'bull'
2 import { move, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { addIntroOutro, addWatermark, cutVideo } from '@server/helpers/ffmpeg'
5 import { createTorrentAndSetInfoHashFromPath } from '@server/helpers/webtorrent'
6 import { CONFIG } from '@server/initializers/config'
7 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
8 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
9 import { VideoTranscodingProfilesManager } from '@server/lib/transcoding/default-transcoding-profiles'
10 import { isAbleToUploadVideo } from '@server/lib/user'
11 import { addOptimizeOrMergeAudioJob } from '@server/lib/video'
12 import { removeHLSPlaylist, removeWebTorrentFile } from '@server/lib/video-file'
13 import { VideoPathManager } from '@server/lib/video-path-manager'
14 import { approximateIntroOutroAdditionalSize } from '@server/lib/video-studio'
15 import { UserModel } from '@server/models/user/user'
16 import { VideoModel } from '@server/models/video/video'
17 import { VideoFileModel } from '@server/models/video/video-file'
18 import { MVideo, MVideoFile, MVideoFullLight, MVideoId, MVideoWithAllFiles } from '@server/types/models'
19 import { getLowercaseExtension, pick } from '@shared/core-utils'
25 getVideoStreamDimensionsInfo,
26 getVideoStreamDuration,
28 } from '@shared/extra-utils'
30 VideoStudioEditionPayload,
32 VideoStudioTaskCutPayload,
33 VideoStudioTaskIntroPayload,
34 VideoStudioTaskOutroPayload,
35 VideoStudioTaskPayload,
36 VideoStudioTaskWatermarkPayload
37 } from '@shared/models'
38 import { logger, loggerTagsFactory } from '../../../helpers/logger'
40 const lTagsBase = loggerTagsFactory('video-edition')
42 async function processVideoStudioEdition (job: Job) {
43 const payload = job.data as VideoStudioEditionPayload
44 const lTags = lTagsBase(payload.videoUUID)
46 logger.info('Process video studio edition of %s in job %d.', payload.videoUUID, job.id, lTags)
48 const video = await VideoModel.loadFull(payload.videoUUID)
50 // No video, maybe deleted?
52 logger.info('Can\'t process job %d, video does not exist.', job.id, lTags)
56 await checkUserQuotaOrThrow(video, payload)
58 const inputFile = video.getMaxQualityFile()
60 const editionResultPath = await VideoPathManager.Instance.makeAvailableVideoFile(inputFile, async originalFilePath => {
61 let tmpInputFilePath: string
62 let outputPath: string
64 for (const task of payload.tasks) {
65 const outputFilename = buildUUID() + inputFile.extname
66 outputPath = join(CONFIG.STORAGE.TMP_DIR, outputFilename)
69 inputPath: tmpInputFilePath ?? originalFilePath,
76 if (tmpInputFilePath) await remove(tmpInputFilePath)
78 // For the next iteration
79 tmpInputFilePath = outputPath
85 logger.info('Video edition ended for video %s.', video.uuid, lTags)
87 const newFile = await buildNewFile(video, editionResultPath)
89 const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newFile)
90 await move(editionResultPath, outputPath)
92 await createTorrentAndSetInfoHashFromPath(video, newFile, outputPath)
93 await removeAllFiles(video, newFile)
97 video.duration = await getVideoStreamDuration(outputPath)
100 await federateVideoIfNeeded(video, false, undefined)
102 const user = await UserModel.loadByVideoId(video.id)
103 await addOptimizeOrMergeAudioJob({ video, videoFile: newFile, user, isNewVideo: false })
106 // ---------------------------------------------------------------------------
109 processVideoStudioEdition
112 // ---------------------------------------------------------------------------
114 type TaskProcessorOptions <T extends VideoStudioTaskPayload = VideoStudioTaskPayload> = {
119 lTags: { tags: string[] }
122 const taskProcessors: { [id in VideoStudioTask['name']]: (options: TaskProcessorOptions) => Promise<any> } = {
123 'add-intro': processAddIntroOutro,
124 'add-outro': processAddIntroOutro,
126 'add-watermark': processAddWatermark
129 async function processTask (options: TaskProcessorOptions) {
130 const { video, task } = options
132 logger.info('Processing %s task for video %s.', task.name, video.uuid, { task, ...options.lTags })
134 const processor = taskProcessors[options.task.name]
135 if (!process) throw new Error('Unknown task ' + task.name)
137 return processor(options)
140 function processAddIntroOutro (options: TaskProcessorOptions<VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload>) {
141 const { task } = options
143 return addIntroOutro({
144 ...pick(options, [ 'inputPath', 'outputPath' ]),
146 introOutroPath: task.options.file,
147 type: task.name === 'add-intro'
151 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
152 profile: CONFIG.TRANSCODING.PROFILE
156 function processCut (options: TaskProcessorOptions<VideoStudioTaskCutPayload>) {
157 const { task } = options
160 ...pick(options, [ 'inputPath', 'outputPath' ]),
162 start: task.options.start,
163 end: task.options.end
167 function processAddWatermark (options: TaskProcessorOptions<VideoStudioTaskWatermarkPayload>) {
168 const { task } = options
170 return addWatermark({
171 ...pick(options, [ 'inputPath', 'outputPath' ]),
173 watermarkPath: task.options.file,
175 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
176 profile: CONFIG.TRANSCODING.PROFILE
180 async function buildNewFile (video: MVideoId, path: string) {
181 const videoFile = new VideoFileModel({
182 extname: getLowercaseExtension(path),
183 size: await getFileSize(path),
184 metadata: await buildFileMetadata(path),
185 videoStreamingPlaylistId: null,
189 const probe = await ffprobePromise(path)
191 videoFile.fps = await getVideoStreamFPS(path, probe)
192 videoFile.resolution = (await getVideoStreamDimensionsInfo(path, probe)).resolution
194 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
199 async function removeAllFiles (video: MVideoWithAllFiles, webTorrentFileException: MVideoFile) {
200 await removeHLSPlaylist(video)
202 for (const file of video.VideoFiles) {
203 if (file.id === webTorrentFileException.id) continue
205 await removeWebTorrentFile(video, file.id)
209 async function checkUserQuotaOrThrow (video: MVideoFullLight, payload: VideoStudioEditionPayload) {
210 const user = await UserModel.loadByVideoId(video.id)
212 const filePathFinder = (i: number) => (payload.tasks[i] as VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload).options.file
214 const additionalBytes = await approximateIntroOutroAdditionalSize(video, payload.tasks, filePathFinder)
215 if (await isAbleToUploadVideo(user.id, additionalBytes) === false) {
216 throw new Error('Quota exceeded for this user to edit the video')