]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Refactor video views
[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'
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 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
0305db28
JB
84 await VideoPathManager.Instance.makeAvailableVideoFile(videoOrStreamingPlaylist, videoFileInput, videoInputPath => {
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) {
9129b769
C
138 if (payload.isMaxQuality && CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
139 // Remove webtorrent files if not enabled
d7a25329 140 for (const file of video.VideoFiles) {
764b1a14 141 await video.removeFileAndTorrent(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
JB
234 isMaxQuality: payload.isMaxQuality,
235 isNewVideo: payload.isNewVideo
09209296 236 }
77d7e851 237
0305db28 238 await addTranscodingJob(hlsTranscodingPayload, jobOptions)
70243d7a
C
239
240 return true
09209296 241}
24516aa2 242
0305db28
JB
243// ---------------------------------------------------------------------------
244
245export {
246 processVideoTranscoding,
247 createHlsJobIfEnabled,
248 onNewWebTorrentFileResolution
249}
250
251// ---------------------------------------------------------------------------
252
253async function createLowerResolutionsJobs (options: {
254 video: MVideoFullLight
255 user: MUserId
256 videoFileResolution: number
257 isPortraitMode: boolean
258 isNewVideo: boolean
9129b769 259 type: 'hls' | 'webtorrent'
0305db28
JB
260}) {
261 const { video, user, videoFileResolution, isPortraitMode, isNewVideo, type } = options
262
24516aa2
C
263 // Create transcoding jobs if there are enabled resolutions
264 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
5a298a5a 265 const resolutionCreated: string[] = []
24516aa2
C
266
267 for (const resolution of resolutionsEnabled) {
268 let dataInput: VideoTranscodingPayload
269
9129b769 270 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED && type === 'webtorrent') {
24516aa2
C
271 // WebTorrent will create subsequent HLS job
272 dataInput = {
273 type: 'new-resolution-to-webtorrent',
274 videoUUID: video.uuid,
275 resolution,
0305db28
JB
276 isPortraitMode,
277 isNewVideo
24516aa2 278 }
5a298a5a
C
279
280 resolutionCreated.push('webtorrent-' + resolution)
9129b769
C
281 }
282
283 if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') {
24516aa2
C
284 dataInput = {
285 type: 'new-resolution-to-hls',
286 videoUUID: video.uuid,
287 resolution,
288 isPortraitMode,
9129b769 289 copyCodecs: false,
0305db28
JB
290 isMaxQuality: false,
291 isNewVideo
24516aa2 292 }
5a298a5a
C
293
294 resolutionCreated.push('hls-' + resolution)
24516aa2
C
295 }
296
70243d7a
C
297 if (!dataInput) continue
298
77d7e851 299 const jobOptions = {
a6e37eeb 300 priority: await getTranscodingJobPriority(user)
77d7e851
C
301 }
302
0305db28 303 await addTranscodingJob(dataInput, jobOptions)
24516aa2
C
304 }
305
70243d7a 306 if (resolutionCreated.length === 0) {
5a298a5a 307 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid, lTags(video.uuid))
70243d7a
C
308
309 return false
310 }
311
312 logger.info(
313 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution,
5a298a5a 314 { resolutionCreated, ...lTags(video.uuid) }
70243d7a 315 )
24516aa2
C
316
317 return true
318}