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