]>
Commit | Line | Data |
---|---|---|
1 | import { Job } from 'bullmq' | |
2 | import { TranscodeVODOptionsType } from '@server/helpers/ffmpeg' | |
3 | import { Hooks } from '@server/lib/plugins/hooks' | |
4 | import { buildTranscodingJob, getTranscodingJobPriority } from '@server/lib/video' | |
5 | import { VideoPathManager } from '@server/lib/video-path-manager' | |
6 | import { moveToFailedTranscodingState, moveToNextState } from '@server/lib/video-state' | |
7 | import { UserModel } from '@server/models/user/user' | |
8 | import { VideoJobInfoModel } from '@server/models/video/video-job-info' | |
9 | import { MUser, MUserId, MVideo, MVideoFullLight, MVideoWithFile } from '@server/types/models' | |
10 | import { pick } from '@shared/core-utils' | |
11 | import { | |
12 | HLSTranscodingPayload, | |
13 | MergeAudioTranscodingPayload, | |
14 | NewWebTorrentResolutionTranscodingPayload, | |
15 | OptimizeTranscodingPayload, | |
16 | VideoTranscodingPayload | |
17 | } from '@shared/models' | |
18 | import { retryTransactionWrapper } from '../../../helpers/database-utils' | |
19 | import { computeResolutionsToTranscode } from '../../../helpers/ffmpeg' | |
20 | import { logger, loggerTagsFactory } from '../../../helpers/logger' | |
21 | import { CONFIG } from '../../../initializers/config' | |
22 | import { VideoModel } from '../../../models/video/video' | |
23 | import { | |
24 | generateHlsPlaylistResolution, | |
25 | mergeAudioVideofile, | |
26 | optimizeOriginalVideofile, | |
27 | transcodeNewWebTorrentResolution | |
28 | } from '../../transcoding/transcoding' | |
29 | import { JobQueue } from '../job-queue' | |
30 | ||
31 | type HandlerFunction = (job: Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<void> | |
32 | ||
33 | const handlers: { [ id in VideoTranscodingPayload['type'] ]: HandlerFunction } = { | |
34 | 'new-resolution-to-hls': handleHLSJob, | |
35 | 'new-resolution-to-webtorrent': handleNewWebTorrentResolutionJob, | |
36 | 'merge-audio-to-webtorrent': handleWebTorrentMergeAudioJob, | |
37 | 'optimize-to-webtorrent': handleWebTorrentOptimizeJob | |
38 | } | |
39 | ||
40 | const lTags = loggerTagsFactory('transcoding') | |
41 | ||
42 | async function processVideoTranscoding (job: Job) { | |
43 | const payload = job.data as VideoTranscodingPayload | |
44 | logger.info('Processing transcoding job %s.', job.id, lTags(payload.videoUUID)) | |
45 | ||
46 | const video = await VideoModel.loadFull(payload.videoUUID) | |
47 | // No video, maybe deleted? | |
48 | if (!video) { | |
49 | logger.info('Do not process job %d, video does not exist.', job.id, lTags(payload.videoUUID)) | |
50 | return undefined | |
51 | } | |
52 | ||
53 | const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId) | |
54 | ||
55 | const handler = handlers[payload.type] | |
56 | ||
57 | if (!handler) { | |
58 | await moveToFailedTranscodingState(video) | |
59 | await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') | |
60 | ||
61 | throw new Error('Cannot find transcoding handler for ' + payload.type) | |
62 | } | |
63 | ||
64 | try { | |
65 | await handler(job, payload, video, user) | |
66 | } catch (error) { | |
67 | await moveToFailedTranscodingState(video) | |
68 | ||
69 | await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') | |
70 | ||
71 | throw error | |
72 | } | |
73 | ||
74 | return video | |
75 | } | |
76 | ||
77 | // --------------------------------------------------------------------------- | |
78 | ||
79 | export { | |
80 | processVideoTranscoding | |
81 | } | |
82 | ||
83 | // --------------------------------------------------------------------------- | |
84 | // Job handlers | |
85 | // --------------------------------------------------------------------------- | |
86 | ||
87 | async function handleHLSJob (job: Job, payload: HLSTranscodingPayload, video: MVideoFullLight, user: MUser) { | |
88 | logger.info('Handling HLS transcoding job for %s.', video.uuid, lTags(video.uuid)) | |
89 | ||
90 | const videoFileInput = payload.copyCodecs | |
91 | ? video.getWebTorrentFile(payload.resolution) | |
92 | : video.getMaxQualityFile() | |
93 | ||
94 | const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist() | |
95 | ||
96 | const inputFileMutexReleaser = await VideoPathManager.Instance.lockFiles(video.uuid) | |
97 | ||
98 | try { | |
99 | await videoFileInput.getVideo().reload() | |
100 | ||
101 | await VideoPathManager.Instance.makeAvailableVideoFile(videoFileInput.withVideoOrPlaylist(videoOrStreamingPlaylist), videoInputPath => { | |
102 | return generateHlsPlaylistResolution({ | |
103 | video, | |
104 | videoInputPath, | |
105 | inputFileMutexReleaser, | |
106 | resolution: payload.resolution, | |
107 | copyCodecs: payload.copyCodecs, | |
108 | job | |
109 | }) | |
110 | }) | |
111 | } finally { | |
112 | inputFileMutexReleaser() | |
113 | } | |
114 | ||
115 | logger.info('HLS transcoding job for %s ended.', video.uuid, lTags(video.uuid)) | |
116 | ||
117 | await onHlsPlaylistGeneration(video, user, payload) | |
118 | } | |
119 | ||
120 | async function handleNewWebTorrentResolutionJob ( | |
121 | job: Job, | |
122 | payload: NewWebTorrentResolutionTranscodingPayload, | |
123 | video: MVideoFullLight, | |
124 | user: MUserId | |
125 | ) { | |
126 | logger.info('Handling WebTorrent transcoding job for %s.', video.uuid, lTags(video.uuid)) | |
127 | ||
128 | await transcodeNewWebTorrentResolution({ video, resolution: payload.resolution, job }) | |
129 | ||
130 | logger.info('WebTorrent transcoding job for %s ended.', video.uuid, lTags(video.uuid)) | |
131 | ||
132 | await onNewWebTorrentFileResolution(video, user, payload) | |
133 | } | |
134 | ||
135 | async function handleWebTorrentMergeAudioJob (job: Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) { | |
136 | logger.info('Handling merge audio transcoding job for %s.', video.uuid, lTags(video.uuid)) | |
137 | ||
138 | await mergeAudioVideofile({ video, resolution: payload.resolution, job }) | |
139 | ||
140 | logger.info('Merge audio transcoding job for %s ended.', video.uuid, lTags(video.uuid)) | |
141 | ||
142 | await onVideoFirstWebTorrentTranscoding(video, payload, 'video', user) | |
143 | } | |
144 | ||
145 | async function handleWebTorrentOptimizeJob (job: Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) { | |
146 | logger.info('Handling optimize transcoding job for %s.', video.uuid, lTags(video.uuid)) | |
147 | ||
148 | const { transcodeType } = await optimizeOriginalVideofile({ video, inputVideoFile: video.getMaxQualityFile(), job }) | |
149 | ||
150 | logger.info('Optimize transcoding job for %s ended.', video.uuid, lTags(video.uuid)) | |
151 | ||
152 | await onVideoFirstWebTorrentTranscoding(video, payload, transcodeType, user) | |
153 | } | |
154 | ||
155 | // --------------------------------------------------------------------------- | |
156 | ||
157 | async function onHlsPlaylistGeneration (video: MVideoFullLight, user: MUser, payload: HLSTranscodingPayload) { | |
158 | if (payload.isMaxQuality && payload.autoDeleteWebTorrentIfNeeded && CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) { | |
159 | // Remove webtorrent files if not enabled | |
160 | for (const file of video.VideoFiles) { | |
161 | await video.removeWebTorrentFile(file) | |
162 | await file.destroy() | |
163 | } | |
164 | ||
165 | video.VideoFiles = [] | |
166 | ||
167 | // Create HLS new resolution jobs | |
168 | await createLowerResolutionsJobs({ | |
169 | video, | |
170 | user, | |
171 | videoFileResolution: payload.resolution, | |
172 | hasAudio: payload.hasAudio, | |
173 | isNewVideo: payload.isNewVideo ?? true, | |
174 | type: 'hls' | |
175 | }) | |
176 | } | |
177 | ||
178 | await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') | |
179 | await retryTransactionWrapper(moveToNextState, { video, isNewVideo: payload.isNewVideo }) | |
180 | } | |
181 | ||
182 | async function onVideoFirstWebTorrentTranscoding ( | |
183 | videoArg: MVideoWithFile, | |
184 | payload: OptimizeTranscodingPayload | MergeAudioTranscodingPayload, | |
185 | transcodeType: TranscodeVODOptionsType, | |
186 | user: MUserId | |
187 | ) { | |
188 | const mutexReleaser = await VideoPathManager.Instance.lockFiles(videoArg.uuid) | |
189 | ||
190 | try { | |
191 | // Maybe the video changed in database, refresh it | |
192 | const videoDatabase = await VideoModel.loadFull(videoArg.uuid) | |
193 | // Video does not exist anymore | |
194 | if (!videoDatabase) return undefined | |
195 | ||
196 | const { resolution, audioStream } = await videoDatabase.probeMaxQualityFile() | |
197 | ||
198 | // Generate HLS version of the original file | |
199 | const originalFileHLSPayload = { | |
200 | ...payload, | |
201 | ||
202 | hasAudio: !!audioStream, | |
203 | resolution: videoDatabase.getMaxQualityFile().resolution, | |
204 | // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues | |
205 | copyCodecs: transcodeType !== 'quick-transcode', | |
206 | isMaxQuality: true | |
207 | } | |
208 | const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload) | |
209 | const hasNewResolutions = await createLowerResolutionsJobs({ | |
210 | video: videoDatabase, | |
211 | user, | |
212 | videoFileResolution: resolution, | |
213 | hasAudio: !!audioStream, | |
214 | type: 'webtorrent', | |
215 | isNewVideo: payload.isNewVideo ?? true | |
216 | }) | |
217 | ||
218 | await VideoJobInfoModel.decrease(videoDatabase.uuid, 'pendingTranscode') | |
219 | ||
220 | // Move to next state if there are no other resolutions to generate | |
221 | if (!hasHls && !hasNewResolutions) { | |
222 | await retryTransactionWrapper(moveToNextState, { video: videoDatabase, isNewVideo: payload.isNewVideo }) | |
223 | } | |
224 | } finally { | |
225 | mutexReleaser() | |
226 | } | |
227 | } | |
228 | ||
229 | async function onNewWebTorrentFileResolution ( | |
230 | video: MVideo, | |
231 | user: MUserId, | |
232 | payload: NewWebTorrentResolutionTranscodingPayload | MergeAudioTranscodingPayload | |
233 | ) { | |
234 | if (payload.createHLSIfNeeded) { | |
235 | await createHlsJobIfEnabled(user, { hasAudio: true, copyCodecs: true, isMaxQuality: false, ...payload }) | |
236 | } | |
237 | ||
238 | await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') | |
239 | ||
240 | await retryTransactionWrapper(moveToNextState, { video, isNewVideo: payload.isNewVideo }) | |
241 | } | |
242 | ||
243 | // --------------------------------------------------------------------------- | |
244 | ||
245 | async function createHlsJobIfEnabled (user: MUserId, payload: { | |
246 | videoUUID: string | |
247 | resolution: number | |
248 | hasAudio: boolean | |
249 | copyCodecs: boolean | |
250 | isMaxQuality: boolean | |
251 | isNewVideo?: boolean | |
252 | }) { | |
253 | if (!payload || CONFIG.TRANSCODING.ENABLED !== true || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false | |
254 | ||
255 | const jobOptions = { | |
256 | priority: await getTranscodingJobPriority(user) | |
257 | } | |
258 | ||
259 | const hlsTranscodingPayload: HLSTranscodingPayload = { | |
260 | type: 'new-resolution-to-hls', | |
261 | autoDeleteWebTorrentIfNeeded: true, | |
262 | ||
263 | ...pick(payload, [ 'videoUUID', 'resolution', 'copyCodecs', 'isMaxQuality', 'isNewVideo', 'hasAudio' ]) | |
264 | } | |
265 | ||
266 | await JobQueue.Instance.createJob(await buildTranscodingJob(hlsTranscodingPayload, jobOptions)) | |
267 | ||
268 | return true | |
269 | } | |
270 | ||
271 | async function createLowerResolutionsJobs (options: { | |
272 | video: MVideoFullLight | |
273 | user: MUserId | |
274 | videoFileResolution: number | |
275 | hasAudio: boolean | |
276 | isNewVideo: boolean | |
277 | type: 'hls' | 'webtorrent' | |
278 | }) { | |
279 | const { video, user, videoFileResolution, isNewVideo, hasAudio, type } = options | |
280 | ||
281 | // Create transcoding jobs if there are enabled resolutions | |
282 | const resolutionsEnabled = await Hooks.wrapObject( | |
283 | computeResolutionsToTranscode({ input: videoFileResolution, type: 'vod', includeInput: false, strictLower: true, hasAudio }), | |
284 | 'filter:transcoding.auto.resolutions-to-transcode.result', | |
285 | options | |
286 | ) | |
287 | ||
288 | const resolutionCreated: string[] = [] | |
289 | ||
290 | for (const resolution of resolutionsEnabled) { | |
291 | let dataInput: VideoTranscodingPayload | |
292 | ||
293 | if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED && type === 'webtorrent') { | |
294 | // WebTorrent will create subsequent HLS job | |
295 | dataInput = { | |
296 | type: 'new-resolution-to-webtorrent', | |
297 | videoUUID: video.uuid, | |
298 | resolution, | |
299 | hasAudio, | |
300 | createHLSIfNeeded: true, | |
301 | isNewVideo | |
302 | } | |
303 | ||
304 | resolutionCreated.push('webtorrent-' + resolution) | |
305 | } | |
306 | ||
307 | if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') { | |
308 | dataInput = { | |
309 | type: 'new-resolution-to-hls', | |
310 | videoUUID: video.uuid, | |
311 | resolution, | |
312 | hasAudio, | |
313 | copyCodecs: false, | |
314 | isMaxQuality: false, | |
315 | autoDeleteWebTorrentIfNeeded: true, | |
316 | isNewVideo | |
317 | } | |
318 | ||
319 | resolutionCreated.push('hls-' + resolution) | |
320 | } | |
321 | ||
322 | if (!dataInput) continue | |
323 | ||
324 | const jobOptions = { | |
325 | priority: await getTranscodingJobPriority(user) | |
326 | } | |
327 | ||
328 | await JobQueue.Instance.createJob(await buildTranscodingJob(dataInput, jobOptions)) | |
329 | } | |
330 | ||
331 | if (resolutionCreated.length === 0) { | |
332 | logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid, lTags(video.uuid)) | |
333 | ||
334 | return false | |
335 | } | |
336 | ||
337 | logger.info( | |
338 | 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution, | |
339 | { resolutionCreated, ...lTags(video.uuid) } | |
340 | ) | |
341 | ||
342 | return true | |
343 | } |