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