]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-studio-edition.ts
Move to bullmq
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-studio-edition.ts
CommitLineData
5a921e7b 1import { Job } from 'bullmq'
c729caf6
C
2import { move, remove } from 'fs-extra'
3import { join } from 'path'
4import { addIntroOutro, addWatermark, cutVideo } from '@server/helpers/ffmpeg'
5import { createTorrentAndSetInfoHashFromPath } from '@server/helpers/webtorrent'
6import { CONFIG } from '@server/initializers/config'
7import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
8import { generateWebTorrentVideoFilename } from '@server/lib/paths'
9import { VideoTranscodingProfilesManager } from '@server/lib/transcoding/default-transcoding-profiles'
10import { isAbleToUploadVideo } from '@server/lib/user'
1808a1f8 11import { addOptimizeOrMergeAudioJob } from '@server/lib/video'
1bb4c9ab 12import { removeHLSPlaylist, removeWebTorrentFile } from '@server/lib/video-file'
c729caf6 13import { VideoPathManager } from '@server/lib/video-path-manager'
92e66e04 14import { approximateIntroOutroAdditionalSize } from '@server/lib/video-studio'
c729caf6
C
15import { UserModel } from '@server/models/user/user'
16import { VideoModel } from '@server/models/video/video'
17import { VideoFileModel } from '@server/models/video/video-file'
18import { MVideo, MVideoFile, MVideoFullLight, MVideoId, MVideoWithAllFiles } from '@server/types/models'
19import { getLowercaseExtension, pick } from '@shared/core-utils'
20import {
21 buildFileMetadata,
22 buildUUID,
23 ffprobePromise,
24 getFileSize,
25 getVideoStreamDimensionsInfo,
26 getVideoStreamDuration,
27 getVideoStreamFPS
28} from '@shared/extra-utils'
29import {
92e66e04 30 VideoStudioEditionPayload,
1bb4c9ab 31 VideoStudioTask,
92e66e04
C
32 VideoStudioTaskCutPayload,
33 VideoStudioTaskIntroPayload,
34 VideoStudioTaskOutroPayload,
1bb4c9ab
C
35 VideoStudioTaskPayload,
36 VideoStudioTaskWatermarkPayload
c729caf6
C
37} from '@shared/models'
38import { logger, loggerTagsFactory } from '../../../helpers/logger'
39
40const lTagsBase = loggerTagsFactory('video-edition')
41
92e66e04
C
42async function processVideoStudioEdition (job: Job) {
43 const payload = job.data as VideoStudioEditionPayload
1808a1f8 44 const lTags = lTagsBase(payload.videoUUID)
c729caf6 45
92e66e04 46 logger.info('Process video studio edition of %s in job %d.', payload.videoUUID, job.id, lTags)
c729caf6 47
4fae2b1f 48 const video = await VideoModel.loadFull(payload.videoUUID)
c729caf6
C
49
50 // No video, maybe deleted?
51 if (!video) {
1808a1f8 52 logger.info('Can\'t process job %d, video does not exist.', job.id, lTags)
c729caf6
C
53 return undefined
54 }
55
56 await checkUserQuotaOrThrow(video, payload)
57
58 const inputFile = video.getMaxQualityFile()
59
60 const editionResultPath = await VideoPathManager.Instance.makeAvailableVideoFile(inputFile, async originalFilePath => {
61 let tmpInputFilePath: string
62 let outputPath: string
63
64 for (const task of payload.tasks) {
65 const outputFilename = buildUUID() + inputFile.extname
66 outputPath = join(CONFIG.STORAGE.TMP_DIR, outputFilename)
67
68 await processTask({
69 inputPath: tmpInputFilePath ?? originalFilePath,
70 video,
71 outputPath,
1808a1f8
C
72 task,
73 lTags
c729caf6
C
74 })
75
76 if (tmpInputFilePath) await remove(tmpInputFilePath)
77
78 // For the next iteration
79 tmpInputFilePath = outputPath
80 }
81
82 return outputPath
83 })
84
1808a1f8 85 logger.info('Video edition ended for video %s.', video.uuid, lTags)
c729caf6
C
86
87 const newFile = await buildNewFile(video, editionResultPath)
88
89 const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newFile)
90 await move(editionResultPath, outputPath)
91
92 await createTorrentAndSetInfoHashFromPath(video, newFile, outputPath)
c729caf6
C
93 await removeAllFiles(video, newFile)
94
95 await newFile.save()
96
c729caf6
C
97 video.duration = await getVideoStreamDuration(outputPath)
98 await video.save()
99
100 await federateVideoIfNeeded(video, false, undefined)
101
1808a1f8
C
102 const user = await UserModel.loadByVideoId(video.id)
103 await addOptimizeOrMergeAudioJob({ video, videoFile: newFile, user, isNewVideo: false })
c729caf6
C
104}
105
106// ---------------------------------------------------------------------------
107
108export {
92e66e04 109 processVideoStudioEdition
c729caf6
C
110}
111
112// ---------------------------------------------------------------------------
113
92e66e04 114type TaskProcessorOptions <T extends VideoStudioTaskPayload = VideoStudioTaskPayload> = {
c729caf6
C
115 inputPath: string
116 outputPath: string
117 video: MVideo
118 task: T
1808a1f8 119 lTags: { tags: string[] }
c729caf6
C
120}
121
92e66e04 122const taskProcessors: { [id in VideoStudioTask['name']]: (options: TaskProcessorOptions) => Promise<any> } = {
c729caf6
C
123 'add-intro': processAddIntroOutro,
124 'add-outro': processAddIntroOutro,
125 'cut': processCut,
126 'add-watermark': processAddWatermark
127}
128
129async function processTask (options: TaskProcessorOptions) {
130 const { video, task } = options
131
1808a1f8 132 logger.info('Processing %s task for video %s.', task.name, video.uuid, { task, ...options.lTags })
c729caf6
C
133
134 const processor = taskProcessors[options.task.name]
135 if (!process) throw new Error('Unknown task ' + task.name)
136
137 return processor(options)
138}
139
92e66e04 140function processAddIntroOutro (options: TaskProcessorOptions<VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload>) {
c729caf6
C
141 const { task } = options
142
143 return addIntroOutro({
144 ...pick(options, [ 'inputPath', 'outputPath' ]),
145
146 introOutroPath: task.options.file,
147 type: task.name === 'add-intro'
148 ? 'intro'
149 : 'outro',
150
151 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
152 profile: CONFIG.TRANSCODING.PROFILE
153 })
154}
155
92e66e04 156function processCut (options: TaskProcessorOptions<VideoStudioTaskCutPayload>) {
c729caf6
C
157 const { task } = options
158
159 return cutVideo({
160 ...pick(options, [ 'inputPath', 'outputPath' ]),
161
162 start: task.options.start,
163 end: task.options.end
164 })
165}
166
92e66e04 167function processAddWatermark (options: TaskProcessorOptions<VideoStudioTaskWatermarkPayload>) {
c729caf6
C
168 const { task } = options
169
170 return addWatermark({
171 ...pick(options, [ 'inputPath', 'outputPath' ]),
172
173 watermarkPath: task.options.file,
174
175 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
176 profile: CONFIG.TRANSCODING.PROFILE
177 })
178}
179
180async 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,
186 videoId: video.id
187 })
188
189 const probe = await ffprobePromise(path)
190
191 videoFile.fps = await getVideoStreamFPS(path, probe)
192 videoFile.resolution = (await getVideoStreamDimensionsInfo(path, probe)).resolution
193
194 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
195
196 return videoFile
197}
198
199async function removeAllFiles (video: MVideoWithAllFiles, webTorrentFileException: MVideoFile) {
1bb4c9ab 200 await removeHLSPlaylist(video)
c729caf6
C
201
202 for (const file of video.VideoFiles) {
203 if (file.id === webTorrentFileException.id) continue
204
1bb4c9ab 205 await removeWebTorrentFile(video, file.id)
c729caf6
C
206 }
207}
208
92e66e04 209async function checkUserQuotaOrThrow (video: MVideoFullLight, payload: VideoStudioEditionPayload) {
c729caf6
C
210 const user = await UserModel.loadByVideoId(video.id)
211
92e66e04 212 const filePathFinder = (i: number) => (payload.tasks[i] as VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload).options.file
c729caf6
C
213
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')
217 }
218}