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