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