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