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