]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Lock files to generate torrents/move files
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-transcoding.ts
CommitLineData
5a921e7b 1import { Job } from 'bullmq'
c729caf6 2import { TranscodeVODOptionsType } from '@server/helpers/ffmpeg'
84cae54e 3import { Hooks } from '@server/lib/plugins/hooks'
b42c2c7e 4import { buildTranscodingJob, getTranscodingJobPriority } from '@server/lib/video'
0305db28 5import { VideoPathManager } from '@server/lib/video-path-manager'
221ee1ad 6import { moveToFailedTranscodingState, moveToNextState } from '@server/lib/video-state'
7d9ba5c0 7import { UserModel } from '@server/models/user/user'
0305db28
JB
8import { VideoJobInfoModel } from '@server/models/video/video-job-info'
9import { MUser, MUserId, MVideo, MVideoFullLight, MVideoWithFile } from '@server/types/models'
cbe2f36d 10import { pick } from '@shared/core-utils'
8dc8a34e 11import {
24516aa2 12 HLSTranscodingPayload,
8dc8a34e 13 MergeAudioTranscodingPayload,
0f11ec8d 14 NewWebTorrentResolutionTranscodingPayload,
8dc8a34e 15 OptimizeTranscodingPayload,
cbe2f36d 16 VideoResolution,
8dc8a34e 17 VideoTranscodingPayload
d17c7b4e 18} from '@shared/models'
b5b68755 19import { retryTransactionWrapper } from '../../../helpers/database-utils'
84cae54e 20import { computeResolutionsToTranscode } from '../../../helpers/ffmpeg'
5a298a5a 21import { logger, loggerTagsFactory } from '../../../helpers/logger'
b5b68755 22import { CONFIG } from '../../../initializers/config'
3fd3ab2d 23import { VideoModel } from '../../../models/video/video'
24516aa2
C
24import {
25 generateHlsPlaylistResolution,
26 mergeAudioVideofile,
27 optimizeOriginalVideofile,
28 transcodeNewWebTorrentResolution
c729caf6 29} from '../../transcoding/transcoding'
b42c2c7e 30import { JobQueue } from '../job-queue'
24516aa2 31
41fb13c3 32type HandlerFunction = (job: Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<void>
77d7e851 33
e83d06a7 34const handlers: { [ id in VideoTranscodingPayload['type'] ]: HandlerFunction } = {
24516aa2 35 'new-resolution-to-hls': handleHLSJob,
24516aa2 36 'new-resolution-to-webtorrent': handleNewWebTorrentResolutionJob,
24516aa2 37 'merge-audio-to-webtorrent': handleWebTorrentMergeAudioJob,
24516aa2
C
38 'optimize-to-webtorrent': handleWebTorrentOptimizeJob
39}
40298b02 40
5a298a5a
C
41const lTags = loggerTagsFactory('transcoding')
42
41fb13c3 43async function processVideoTranscoding (job: Job) {
a0327eed 44 const payload = job.data as VideoTranscodingPayload
51335c72 45 logger.info('Processing transcoding job %s.', job.id, lTags(payload.videoUUID))
94a5ff8a 46
4fae2b1f 47 const video = await VideoModel.loadFull(payload.videoUUID)
f5028693
C
48 // No video, maybe deleted?
49 if (!video) {
5a298a5a 50 logger.info('Do not process job %d, video does not exist.', job.id, lTags(payload.videoUUID))
f5028693
C
51 return undefined
52 }
53
77d7e851
C
54 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
55
24516aa2 56 const handler = handlers[payload.type]
b5b68755 57
24516aa2 58 if (!handler) {
221ee1ad 59 await moveToFailedTranscodingState(video)
025d858e 60 await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode')
221ee1ad 61
24516aa2
C
62 throw new Error('Cannot find transcoding handler for ' + payload.type)
63 }
b5b68755 64
4e29f4fe 65 try {
66 await handler(job, payload, video, user)
67 } catch (error) {
221ee1ad 68 await moveToFailedTranscodingState(video)
4e29f4fe 69
025d858e
C
70 await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode')
71
4e29f4fe 72 throw error
73 }
24516aa2
C
74
75 return video
76}
09209296 77
025d858e
C
78// ---------------------------------------------------------------------------
79
80export {
81 processVideoTranscoding
82}
83
24516aa2
C
84// ---------------------------------------------------------------------------
85// Job handlers
86// ---------------------------------------------------------------------------
2186386c 87
41fb13c3 88async function handleHLSJob (job: Job, payload: HLSTranscodingPayload, video: MVideoFullLight, user: MUser) {
5a298a5a
C
89 logger.info('Handling HLS transcoding job for %s.', video.uuid, lTags(video.uuid))
90
24516aa2
C
91 const videoFileInput = payload.copyCodecs
92 ? video.getWebTorrentFile(payload.resolution)
93 : video.getMaxQualityFile()
94
95 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
24516aa2 96
3545e72c
C
97 const inputFileMutexReleaser = await VideoPathManager.Instance.lockFiles(video.uuid)
98
99 try {
100 await videoFileInput.getVideo().reload()
101
102 await VideoPathManager.Instance.makeAvailableVideoFile(videoFileInput.withVideoOrPlaylist(videoOrStreamingPlaylist), videoInputPath => {
103 return generateHlsPlaylistResolution({
104 video,
105 videoInputPath,
106 inputFileMutexReleaser,
107 resolution: payload.resolution,
108 copyCodecs: payload.copyCodecs,
109 job
110 })
0305db28 111 })
3545e72c
C
112 } finally {
113 inputFileMutexReleaser()
114 }
536598cf 115
5a298a5a
C
116 logger.info('HLS transcoding job for %s ended.', video.uuid, lTags(video.uuid))
117
fa7388f0 118 await onHlsPlaylistGeneration(video, user, payload)
24516aa2 119}
2186386c 120
77d7e851 121async function handleNewWebTorrentResolutionJob (
41fb13c3 122 job: Job,
0f11ec8d 123 payload: NewWebTorrentResolutionTranscodingPayload,
77d7e851
C
124 video: MVideoFullLight,
125 user: MUserId
126) {
5a298a5a
C
127 logger.info('Handling WebTorrent transcoding job for %s.', video.uuid, lTags(video.uuid))
128
84cae54e 129 await transcodeNewWebTorrentResolution({ video, resolution: payload.resolution, job })
031094f7 130
5a298a5a
C
131 logger.info('WebTorrent transcoding job for %s ended.', video.uuid, lTags(video.uuid))
132
fa7388f0 133 await onNewWebTorrentFileResolution(video, user, payload)
24516aa2
C
134}
135
41fb13c3 136async function handleWebTorrentMergeAudioJob (job: Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
5a298a5a
C
137 logger.info('Handling merge audio transcoding job for %s.', video.uuid, lTags(video.uuid))
138
84cae54e 139 await mergeAudioVideofile({ video, resolution: payload.resolution, job })
24516aa2 140
5a298a5a
C
141 logger.info('Merge audio transcoding job for %s ended.', video.uuid, lTags(video.uuid))
142
025d858e 143 await onVideoFirstWebTorrentTranscoding(video, payload, 'video', user)
40298b02
C
144}
145
41fb13c3 146async function handleWebTorrentOptimizeJob (job: Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
5a298a5a
C
147 logger.info('Handling optimize transcoding job for %s.', video.uuid, lTags(video.uuid))
148
84cae54e 149 const { transcodeType } = await optimizeOriginalVideofile({ video, inputVideoFile: video.getMaxQualityFile(), job })
24516aa2 150
5a298a5a
C
151 logger.info('Optimize transcoding job for %s ended.', video.uuid, lTags(video.uuid))
152
025d858e 153 await onVideoFirstWebTorrentTranscoding(video, payload, transcodeType, user)
24516aa2
C
154}
155
156// ---------------------------------------------------------------------------
157
9129b769 158async function onHlsPlaylistGeneration (video: MVideoFullLight, user: MUser, payload: HLSTranscodingPayload) {
ad5db104 159 if (payload.isMaxQuality && payload.autoDeleteWebTorrentIfNeeded && CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
9129b769 160 // Remove webtorrent files if not enabled
d7a25329 161 for (const file of video.VideoFiles) {
1bb4c9ab 162 await video.removeWebTorrentFile(file)
d7a25329 163 await file.destroy()
1b952dd4 164 }
2186386c 165
d7a25329 166 video.VideoFiles = []
9129b769
C
167
168 // Create HLS new resolution jobs
0305db28
JB
169 await createLowerResolutionsJobs({
170 video,
171 user,
172 videoFileResolution: payload.resolution,
cbe2f36d 173 hasAudio: payload.hasAudio,
0305db28
JB
174 isNewVideo: payload.isNewVideo ?? true,
175 type: 'hls'
176 })
d7a25329 177 }
94a5ff8a 178
0305db28 179 await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode')
1808a1f8 180 await retryTransactionWrapper(moveToNextState, { video, isNewVideo: payload.isNewVideo })
d7a25329 181}
e8d246d5 182
025d858e 183async function onVideoFirstWebTorrentTranscoding (
236841a1 184 videoArg: MVideoWithFile,
9129b769 185 payload: OptimizeTranscodingPayload | MergeAudioTranscodingPayload,
c729caf6 186 transcodeType: TranscodeVODOptionsType,
77d7e851 187 user: MUserId
236841a1 188) {
3545e72c
C
189 const mutexReleaser = await VideoPathManager.Instance.lockFiles(videoArg.uuid)
190
191 try {
192 // Maybe the video changed in database, refresh it
193 const videoDatabase = await VideoModel.loadFull(videoArg.uuid)
194 // Video does not exist anymore
195 if (!videoDatabase) return undefined
196
197 const { resolution, audioStream } = await videoDatabase.probeMaxQualityFile()
198
199 // Generate HLS version of the original file
200 const originalFileHLSPayload = {
201 ...payload,
202
203 hasAudio: !!audioStream,
204 resolution: videoDatabase.getMaxQualityFile().resolution,
205 // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues
206 copyCodecs: transcodeType !== 'quick-transcode',
207 isMaxQuality: true
208 }
209 const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
210 const hasNewResolutions = await createLowerResolutionsJobs({
211 video: videoDatabase,
212 user,
213 videoFileResolution: resolution,
214 hasAudio: !!audioStream,
215 type: 'webtorrent',
216 isNewVideo: payload.isNewVideo ?? true
217 })
218
219 await VideoJobInfoModel.decrease(videoDatabase.uuid, 'pendingTranscode')
220
221 // Move to next state if there are no other resolutions to generate
222 if (!hasHls && !hasNewResolutions) {
223 await retryTransactionWrapper(moveToNextState, { video: videoDatabase, isNewVideo: payload.isNewVideo })
224 }
225 } finally {
226 mutexReleaser()
eae0365b 227 }
40298b02
C
228}
229
24516aa2 230async function onNewWebTorrentFileResolution (
0305db28 231 video: MVideo,
77d7e851 232 user: MUserId,
0f11ec8d 233 payload: NewWebTorrentResolutionTranscodingPayload | MergeAudioTranscodingPayload
24516aa2 234) {
0f11ec8d
C
235 if (payload.createHLSIfNeeded) {
236 await createHlsJobIfEnabled(user, { hasAudio: true, copyCodecs: true, isMaxQuality: false, ...payload })
237 }
238
0305db28 239 await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode')
24516aa2 240
1808a1f8 241 await retryTransactionWrapper(moveToNextState, { video, isNewVideo: payload.isNewVideo })
24516aa2
C
242}
243
025d858e
C
244// ---------------------------------------------------------------------------
245
77d7e851
C
246async function createHlsJobIfEnabled (user: MUserId, payload: {
247 videoUUID: string
248 resolution: number
cbe2f36d 249 hasAudio: boolean
77d7e851 250 copyCodecs: boolean
9129b769 251 isMaxQuality: boolean
0305db28 252 isNewVideo?: boolean
77d7e851 253}) {
0305db28 254 if (!payload || CONFIG.TRANSCODING.ENABLED !== true || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false
77d7e851
C
255
256 const jobOptions = {
a6e37eeb 257 priority: await getTranscodingJobPriority(user)
77d7e851 258 }
09209296 259
77d7e851
C
260 const hlsTranscodingPayload: HLSTranscodingPayload = {
261 type: 'new-resolution-to-hls',
ad5db104 262 autoDeleteWebTorrentIfNeeded: true,
cbe2f36d 263
84cae54e 264 ...pick(payload, [ 'videoUUID', 'resolution', 'copyCodecs', 'isMaxQuality', 'isNewVideo', 'hasAudio' ])
09209296 265 }
77d7e851 266
b42c2c7e 267 await JobQueue.Instance.createJob(await buildTranscodingJob(hlsTranscodingPayload, jobOptions))
70243d7a
C
268
269 return true
09209296 270}
24516aa2 271
0305db28
JB
272async function createLowerResolutionsJobs (options: {
273 video: MVideoFullLight
274 user: MUserId
275 videoFileResolution: number
cbe2f36d 276 hasAudio: boolean
0305db28 277 isNewVideo: boolean
9129b769 278 type: 'hls' | 'webtorrent'
0305db28 279}) {
84cae54e 280 const { video, user, videoFileResolution, isNewVideo, hasAudio, type } = options
0305db28 281
24516aa2 282 // Create transcoding jobs if there are enabled resolutions
ebb9e53a 283 const resolutionsEnabled = await Hooks.wrapObject(
5e2afe42 284 computeResolutionsToTranscode({ input: videoFileResolution, type: 'vod', includeInput: false, strictLower: true }),
64fd6158 285 'filter:transcoding.auto.resolutions-to-transcode.result',
ebb9e53a
C
286 options
287 )
288
5a298a5a 289 const resolutionCreated: string[] = []
24516aa2
C
290
291 for (const resolution of resolutionsEnabled) {
cbe2f36d
C
292 if (resolution === VideoResolution.H_NOVIDEO && hasAudio === false) continue
293
24516aa2
C
294 let dataInput: VideoTranscodingPayload
295
9129b769 296 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED && type === 'webtorrent') {
24516aa2
C
297 // WebTorrent will create subsequent HLS job
298 dataInput = {
299 type: 'new-resolution-to-webtorrent',
300 videoUUID: video.uuid,
301 resolution,
cbe2f36d 302 hasAudio,
0f11ec8d 303 createHLSIfNeeded: true,
0305db28 304 isNewVideo
24516aa2 305 }
5a298a5a
C
306
307 resolutionCreated.push('webtorrent-' + resolution)
9129b769
C
308 }
309
310 if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') {
24516aa2
C
311 dataInput = {
312 type: 'new-resolution-to-hls',
313 videoUUID: video.uuid,
314 resolution,
cbe2f36d 315 hasAudio,
9129b769 316 copyCodecs: false,
0305db28 317 isMaxQuality: false,
ad5db104 318 autoDeleteWebTorrentIfNeeded: true,
0305db28 319 isNewVideo
24516aa2 320 }
5a298a5a
C
321
322 resolutionCreated.push('hls-' + resolution)
24516aa2
C
323 }
324
70243d7a
C
325 if (!dataInput) continue
326
77d7e851 327 const jobOptions = {
a6e37eeb 328 priority: await getTranscodingJobPriority(user)
77d7e851
C
329 }
330
b42c2c7e 331 await JobQueue.Instance.createJob(await buildTranscodingJob(dataInput, jobOptions))
24516aa2
C
332 }
333
70243d7a 334 if (resolutionCreated.length === 0) {
5a298a5a 335 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid, lTags(video.uuid))
70243d7a
C
336
337 return false
338 }
339
340 logger.info(
341 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution,
5a298a5a 342 { resolutionCreated, ...lTags(video.uuid) }
70243d7a 343 )
24516aa2
C
344
345 return true
346}