]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Fix E2E tests
[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'
77d7e851
C
3import { JOB_PRIORITY } from '@server/initializers/constants'
4import { getJobTranscodingPriorityMalus, publishAndFederateIfNeeded } from '@server/lib/video'
b5b68755 5import { getVideoFilePath } from '@server/lib/video-paths'
70243d7a 6import { UserModel } from '@server/models/account/user'
77d7e851 7import { MUser, MUserId, MVideoFullLight, MVideoUUID, MVideoWithFile } from '@server/types/models'
8dc8a34e 8import {
24516aa2 9 HLSTranscodingPayload,
8dc8a34e
C
10 MergeAudioTranscodingPayload,
11 NewResolutionTranscodingPayload,
12 OptimizeTranscodingPayload,
13 VideoTranscodingPayload
14} from '../../../../shared'
b5b68755 15import { retryTransactionWrapper } from '../../../helpers/database-utils'
daf6e480 16import { computeResolutionsToTranscode } from '../../../helpers/ffprobe-utils'
da854ddd 17import { logger } from '../../../helpers/logger'
b5b68755
C
18import { CONFIG } from '../../../initializers/config'
19import { sequelizeTypescript } from '../../../initializers/database'
3fd3ab2d 20import { VideoModel } from '../../../models/video/video'
8dc8a34e 21import { federateVideoIfNeeded } from '../../activitypub/videos'
cef534ed 22import { Notifier } from '../../notifier'
24516aa2
C
23import {
24 generateHlsPlaylistResolution,
25 mergeAudioVideofile,
26 optimizeOriginalVideofile,
27 transcodeNewWebTorrentResolution
28} from '../../video-transcoding'
b5b68755 29import { JobQueue } from '../job-queue'
24516aa2 30
77d7e851
C
31type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
32
33const handlers: { [ id: string ]: HandlerFunction } = {
24516aa2
C
34 // Deprecated, introduced in 3.1
35 'hls': handleHLSJob,
36 'new-resolution-to-hls': handleHLSJob,
37
38 // Deprecated, introduced in 3.1
39 'new-resolution': handleNewWebTorrentResolutionJob,
40 'new-resolution-to-webtorrent': handleNewWebTorrentResolutionJob,
41
42 // Deprecated, introduced in 3.1
43 'merge-audio': handleWebTorrentMergeAudioJob,
44 'merge-audio-to-webtorrent': handleWebTorrentMergeAudioJob,
45
46 // Deprecated, introduced in 3.1
47 'optimize': handleWebTorrentOptimizeJob,
48 'optimize-to-webtorrent': handleWebTorrentOptimizeJob
49}
40298b02 50
a0327eed
C
51async function processVideoTranscoding (job: Bull.Job) {
52 const payload = job.data as VideoTranscodingPayload
94a5ff8a
C
53 logger.info('Processing video file in job %d.', job.id)
54
627621c1 55 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
f5028693
C
56 // No video, maybe deleted?
57 if (!video) {
c1e791ba 58 logger.info('Do not process job %d, video does not exist.', job.id)
f5028693
C
59 return undefined
60 }
61
77d7e851
C
62 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
63
24516aa2 64 const handler = handlers[payload.type]
b5b68755 65
24516aa2
C
66 if (!handler) {
67 throw new Error('Cannot find transcoding handler for ' + payload.type)
68 }
b5b68755 69
77d7e851 70 await handler(job, payload, video, user)
24516aa2
C
71
72 return video
73}
09209296 74
24516aa2
C
75// ---------------------------------------------------------------------------
76// Job handlers
77// ---------------------------------------------------------------------------
2186386c 78
9129b769 79async function handleHLSJob (job: Bull.Job, payload: HLSTranscodingPayload, video: MVideoFullLight, user: MUser) {
24516aa2
C
80 const videoFileInput = payload.copyCodecs
81 ? video.getWebTorrentFile(payload.resolution)
82 : video.getMaxQualityFile()
83
84 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
85 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
86
87 await generateHlsPlaylistResolution({
88 video,
89 videoInputPath,
90 resolution: payload.resolution,
91 copyCodecs: payload.copyCodecs,
92 isPortraitMode: payload.isPortraitMode || false,
93 job
94 })
536598cf 95
9129b769 96 await retryTransactionWrapper(onHlsPlaylistGeneration, video, user, payload)
24516aa2 97}
2186386c 98
77d7e851
C
99async function handleNewWebTorrentResolutionJob (
100 job: Bull.Job,
101 payload: NewResolutionTranscodingPayload,
102 video: MVideoFullLight,
103 user: MUserId
104) {
24516aa2 105 await transcodeNewWebTorrentResolution(video, payload.resolution, payload.isPortraitMode || false, job)
031094f7 106
77d7e851 107 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
24516aa2
C
108}
109
77d7e851 110async function handleWebTorrentMergeAudioJob (job: Bull.Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
111 await mergeAudioVideofile(video, payload.resolution, job)
112
9129b769 113 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, 'video', user)
40298b02
C
114}
115
77d7e851 116async function handleWebTorrentOptimizeJob (job: Bull.Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
117 const transcodeType = await optimizeOriginalVideofile(video, video.getMaxQualityFile(), job)
118
77d7e851 119 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, transcodeType, user)
24516aa2
C
120}
121
122// ---------------------------------------------------------------------------
123
9129b769 124async function onHlsPlaylistGeneration (video: MVideoFullLight, user: MUser, payload: HLSTranscodingPayload) {
09209296
C
125 if (video === undefined) return undefined
126
9129b769
C
127 if (payload.isMaxQuality && CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
128 // Remove webtorrent files if not enabled
d7a25329
C
129 for (const file of video.VideoFiles) {
130 await video.removeFile(file)
90a8bd30 131 await file.removeTorrent()
d7a25329 132 await file.destroy()
1b952dd4 133 }
2186386c 134
d7a25329 135 video.VideoFiles = []
9129b769
C
136
137 // Create HLS new resolution jobs
138 await createLowerResolutionsJobs(video, user, payload.resolution, payload.isPortraitMode, 'hls')
d7a25329 139 }
94a5ff8a 140
d7a25329
C
141 return publishAndFederateIfNeeded(video)
142}
e8d246d5 143
24516aa2 144async function onVideoFileOptimizer (
236841a1 145 videoArg: MVideoWithFile,
9129b769 146 payload: OptimizeTranscodingPayload | MergeAudioTranscodingPayload,
77d7e851
C
147 transcodeType: TranscodeOptionsType,
148 user: MUserId
236841a1 149) {
56b13bd1 150 if (videoArg === undefined) return undefined
031094f7 151
2186386c 152 // Outside the transaction (IO on disk)
dca0fe12 153 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
2186386c 154
dc133480 155 const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
2186386c 156 // Maybe the video changed in database, refresh it
a1587156 157 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
2186386c
C
158 // Video does not exist anymore
159 if (!videoDatabase) return undefined
160
dc133480
C
161 let videoPublished = false
162
24516aa2 163 // Generate HLS version of the original file
236841a1
C
164 const originalFileHLSPayload = Object.assign({}, payload, {
165 isPortraitMode,
166 resolution: videoDatabase.getMaxQualityFile().resolution,
167 // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues
9129b769
C
168 copyCodecs: transcodeType !== 'quick-transcode',
169 isMaxQuality: true
236841a1 170 })
70243d7a 171 const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
d7a25329 172
9129b769 173 const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode, 'webtorrent')
f5028693 174
70243d7a 175 if (!hasHls && !hasNewResolutions) {
2186386c 176 // No transcoding to do, it's now published
d7a25329 177 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
f5028693 178 }
a7977280 179
09209296 180 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
e8d246d5 181
dc133480 182 return { videoDatabase, videoPublished }
2186386c 183 })
e8d246d5 184
5b77537c 185 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
7ccddd7b 186 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
40298b02
C
187}
188
24516aa2
C
189async function onNewWebTorrentFileResolution (
190 video: MVideoUUID,
77d7e851 191 user: MUserId,
69eddafb 192 payload: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
24516aa2
C
193) {
194 await publishAndFederateIfNeeded(video)
195
9129b769 196 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true, isMaxQuality: false }))
24516aa2
C
197}
198
40298b02
C
199// ---------------------------------------------------------------------------
200
201export {
a0327eed 202 processVideoTranscoding,
24516aa2 203 onNewWebTorrentFileResolution
40298b02 204}
09209296
C
205
206// ---------------------------------------------------------------------------
207
77d7e851
C
208async function createHlsJobIfEnabled (user: MUserId, payload: {
209 videoUUID: string
210 resolution: number
211 isPortraitMode?: boolean
212 copyCodecs: boolean
9129b769 213 isMaxQuality: boolean
77d7e851 214}) {
70243d7a 215 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false
77d7e851
C
216
217 const jobOptions = {
218 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
219 }
09209296 220
77d7e851
C
221 const hlsTranscodingPayload: HLSTranscodingPayload = {
222 type: 'new-resolution-to-hls',
223 videoUUID: payload.videoUUID,
224 resolution: payload.resolution,
225 isPortraitMode: payload.isPortraitMode,
9129b769
C
226 copyCodecs: payload.copyCodecs,
227 isMaxQuality: payload.isMaxQuality
09209296 228 }
77d7e851 229
70243d7a
C
230 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
231
232 return true
09209296 233}
24516aa2 234
77d7e851
C
235async function createLowerResolutionsJobs (
236 video: MVideoFullLight,
237 user: MUserId,
238 videoFileResolution: number,
9129b769
C
239 isPortraitMode: boolean,
240 type: 'hls' | 'webtorrent'
77d7e851 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,
255 isPortraitMode
256 }
9129b769
C
257 }
258
259 if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') {
24516aa2
C
260 dataInput = {
261 type: 'new-resolution-to-hls',
262 videoUUID: video.uuid,
263 resolution,
264 isPortraitMode,
9129b769
C
265 copyCodecs: false,
266 isMaxQuality: false
24516aa2
C
267 }
268 }
269
70243d7a
C
270 if (!dataInput) continue
271
272 resolutionCreated.push(resolution)
273
77d7e851
C
274 const jobOptions = {
275 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
276 }
277
278 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
24516aa2
C
279 }
280
70243d7a
C
281 if (resolutionCreated.length === 0) {
282 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
283
284 return false
285 }
286
287 logger.info(
288 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution,
289 { resolutionCreated }
290 )
24516aa2
C
291
292 return true
293}