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