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