]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Generate random uuid for video files
[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
C
127 for (const file of video.VideoFiles) {
128 await video.removeFile(file)
90a8bd30 129 await file.removeTorrent()
d7a25329 130 await file.destroy()
1b952dd4 131 }
2186386c 132
d7a25329 133 video.VideoFiles = []
9129b769
C
134
135 // Create HLS new resolution jobs
136 await createLowerResolutionsJobs(video, user, payload.resolution, payload.isPortraitMode, 'hls')
d7a25329 137 }
94a5ff8a 138
d7a25329
C
139 return publishAndFederateIfNeeded(video)
140}
e8d246d5 141
24516aa2 142async function onVideoFileOptimizer (
236841a1 143 videoArg: MVideoWithFile,
9129b769 144 payload: OptimizeTranscodingPayload | MergeAudioTranscodingPayload,
77d7e851
C
145 transcodeType: TranscodeOptionsType,
146 user: MUserId
236841a1 147) {
56b13bd1 148 if (videoArg === undefined) return undefined
031094f7 149
2186386c 150 // Outside the transaction (IO on disk)
dca0fe12 151 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
2186386c 152
eae0365b
C
153 // Maybe the video changed in database, refresh it
154 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid)
155 // Video does not exist anymore
156 if (!videoDatabase) return undefined
157
158 let videoPublished = false
159
160 // Generate HLS version of the original file
161 const originalFileHLSPayload = Object.assign({}, payload, {
162 isPortraitMode,
163 resolution: videoDatabase.getMaxQualityFile().resolution,
164 // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues
165 copyCodecs: transcodeType !== 'quick-transcode',
166 isMaxQuality: true
167 })
168 const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
a7977280 169
eae0365b 170 const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode, 'webtorrent')
e8d246d5 171
eae0365b
C
172 if (!hasHls && !hasNewResolutions) {
173 // No transcoding to do, it's now published
174 videoPublished = await videoDatabase.publishIfNeededAndSave(undefined)
175 }
176
177 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo)
e8d246d5 178
5b77537c 179 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
7ccddd7b 180 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
40298b02
C
181}
182
24516aa2
C
183async function onNewWebTorrentFileResolution (
184 video: MVideoUUID,
77d7e851 185 user: MUserId,
69eddafb 186 payload: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
24516aa2
C
187) {
188 await publishAndFederateIfNeeded(video)
189
9129b769 190 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true, isMaxQuality: false }))
24516aa2
C
191}
192
40298b02
C
193// ---------------------------------------------------------------------------
194
195export {
a0327eed 196 processVideoTranscoding,
24516aa2 197 onNewWebTorrentFileResolution
40298b02 198}
09209296
C
199
200// ---------------------------------------------------------------------------
201
77d7e851
C
202async function createHlsJobIfEnabled (user: MUserId, payload: {
203 videoUUID: string
204 resolution: number
205 isPortraitMode?: boolean
206 copyCodecs: boolean
9129b769 207 isMaxQuality: boolean
77d7e851 208}) {
70243d7a 209 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false
77d7e851
C
210
211 const jobOptions = {
a6e37eeb 212 priority: await getTranscodingJobPriority(user)
77d7e851 213 }
09209296 214
77d7e851
C
215 const hlsTranscodingPayload: HLSTranscodingPayload = {
216 type: 'new-resolution-to-hls',
217 videoUUID: payload.videoUUID,
218 resolution: payload.resolution,
219 isPortraitMode: payload.isPortraitMode,
9129b769
C
220 copyCodecs: payload.copyCodecs,
221 isMaxQuality: payload.isMaxQuality
09209296 222 }
77d7e851 223
70243d7a
C
224 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
225
226 return true
09209296 227}
24516aa2 228
77d7e851
C
229async function createLowerResolutionsJobs (
230 video: MVideoFullLight,
231 user: MUserId,
232 videoFileResolution: number,
9129b769
C
233 isPortraitMode: boolean,
234 type: 'hls' | 'webtorrent'
77d7e851 235) {
24516aa2
C
236 // Create transcoding jobs if there are enabled resolutions
237 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
70243d7a 238 const resolutionCreated: number[] = []
24516aa2
C
239
240 for (const resolution of resolutionsEnabled) {
241 let dataInput: VideoTranscodingPayload
242
9129b769 243 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED && type === 'webtorrent') {
24516aa2
C
244 // WebTorrent will create subsequent HLS job
245 dataInput = {
246 type: 'new-resolution-to-webtorrent',
247 videoUUID: video.uuid,
248 resolution,
249 isPortraitMode
250 }
9129b769
C
251 }
252
253 if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') {
24516aa2
C
254 dataInput = {
255 type: 'new-resolution-to-hls',
256 videoUUID: video.uuid,
257 resolution,
258 isPortraitMode,
9129b769
C
259 copyCodecs: false,
260 isMaxQuality: false
24516aa2
C
261 }
262 }
263
70243d7a
C
264 if (!dataInput) continue
265
266 resolutionCreated.push(resolution)
267
77d7e851 268 const jobOptions = {
a6e37eeb 269 priority: await getTranscodingJobPriority(user)
77d7e851
C
270 }
271
272 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
24516aa2
C
273 }
274
70243d7a
C
275 if (resolutionCreated.length === 0) {
276 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
277
278 return false
279 }
280
281 logger.info(
282 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution,
283 { resolutionCreated }
284 )
24516aa2
C
285
286 return true
287}