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