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