]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-transcoding.ts
Safely remove webtorrent files
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-transcoding.ts
1 import * as Bull from 'bull'
2 import { TranscodeOptionsType } from '@server/helpers/ffmpeg-utils'
3 import { JOB_PRIORITY } from '@server/initializers/constants'
4 import { getJobTranscodingPriorityMalus, publishAndFederateIfNeeded } from '@server/lib/video'
5 import { getVideoFilePath } from '@server/lib/video-paths'
6 import { MUser, MUserId, MVideoFullLight, MVideoUUID, MVideoWithFile } from '@server/types/models'
7 import {
8 HLSTranscodingPayload,
9 MergeAudioTranscodingPayload,
10 NewResolutionTranscodingPayload,
11 OptimizeTranscodingPayload,
12 VideoTranscodingPayload
13 } from '../../../../shared'
14 import { retryTransactionWrapper } from '../../../helpers/database-utils'
15 import { computeResolutionsToTranscode } from '../../../helpers/ffprobe-utils'
16 import { logger } from '../../../helpers/logger'
17 import { CONFIG } from '../../../initializers/config'
18 import { sequelizeTypescript } from '../../../initializers/database'
19 import { VideoModel } from '../../../models/video/video'
20 import { federateVideoIfNeeded } from '../../activitypub/videos'
21 import { Notifier } from '../../notifier'
22 import {
23 generateHlsPlaylistResolution,
24 mergeAudioVideofile,
25 optimizeOriginalVideofile,
26 transcodeNewWebTorrentResolution
27 } from '../../video-transcoding'
28 import { JobQueue } from '../job-queue'
29 import { UserModel } from '@server/models/account/user'
30
31 type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
32
33 const handlers: { [ id: string ]: HandlerFunction } = {
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 }
50
51 async function processVideoTranscoding (job: Bull.Job) {
52 const payload = job.data as VideoTranscodingPayload
53 logger.info('Processing video file in job %d.', job.id)
54
55 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
56 // No video, maybe deleted?
57 if (!video) {
58 logger.info('Do not process job %d, video does not exist.', job.id)
59 return undefined
60 }
61
62 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
63
64 const handler = handlers[payload.type]
65
66 if (!handler) {
67 throw new Error('Cannot find transcoding handler for ' + payload.type)
68 }
69
70 await handler(job, payload, video, user)
71
72 return video
73 }
74
75 // ---------------------------------------------------------------------------
76 // Job handlers
77 // ---------------------------------------------------------------------------
78
79 async function handleHLSJob (job: Bull.Job, payload: HLSTranscodingPayload, video: MVideoFullLight) {
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 })
95
96 await retryTransactionWrapper(onHlsPlaylistGeneration, video, payload.resolution)
97 }
98
99 async function handleNewWebTorrentResolutionJob (
100 job: Bull.Job,
101 payload: NewResolutionTranscodingPayload,
102 video: MVideoFullLight,
103 user: MUserId
104 ) {
105 await transcodeNewWebTorrentResolution(video, payload.resolution, payload.isPortraitMode || false, job)
106
107 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
108 }
109
110 async function handleWebTorrentMergeAudioJob (job: Bull.Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
111 await mergeAudioVideofile(video, payload.resolution, job)
112
113 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
114 }
115
116 async function handleWebTorrentOptimizeJob (job: Bull.Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
117 const transcodeType = await optimizeOriginalVideofile(video, video.getMaxQualityFile(), job)
118
119 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, transcodeType, user)
120 }
121
122 // ---------------------------------------------------------------------------
123
124 async function onHlsPlaylistGeneration (video: MVideoFullLight, resolution: number) {
125 if (video === undefined) return undefined
126
127 const maxQualityFile = video.getMaxQualityFile()
128
129 // We generated the max quality HLS playlist, we don't need the webtorrent files anymore if the admin disabled it
130 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false && video.hasWebTorrentFiles() && maxQualityFile.resolution === resolution) {
131 for (const file of video.VideoFiles) {
132 await video.removeFile(file)
133 await file.destroy()
134 }
135
136 video.VideoFiles = []
137 }
138
139 return publishAndFederateIfNeeded(video)
140 }
141
142 async function onVideoFileOptimizer (
143 videoArg: MVideoWithFile,
144 payload: OptimizeTranscodingPayload,
145 transcodeType: TranscodeOptionsType,
146 user: MUserId
147 ) {
148 if (videoArg === undefined) return undefined
149
150 // Outside the transaction (IO on disk)
151 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
152
153 const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
154 // Maybe the video changed in database, refresh it
155 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
156 // Video does not exist anymore
157 if (!videoDatabase) return undefined
158
159 let videoPublished = false
160
161 // Generate HLS version of the original file
162 const originalFileHLSPayload = Object.assign({}, payload, {
163 isPortraitMode,
164 resolution: videoDatabase.getMaxQualityFile().resolution,
165 // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues
166 copyCodecs: transcodeType !== 'quick-transcode'
167 })
168 await createHlsJobIfEnabled(user, originalFileHLSPayload)
169
170 const hasNewResolutions = createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode)
171
172 if (!hasNewResolutions) {
173 // No transcoding to do, it's now published
174 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
175 }
176
177 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
178
179 return { videoDatabase, videoPublished }
180 })
181
182 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
183 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
184 }
185
186 async function onNewWebTorrentFileResolution (
187 video: MVideoUUID,
188 user: MUserId,
189 payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
190 ) {
191 await publishAndFederateIfNeeded(video)
192
193 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true }))
194 }
195
196 // ---------------------------------------------------------------------------
197
198 export {
199 processVideoTranscoding,
200 onNewWebTorrentFileResolution
201 }
202
203 // ---------------------------------------------------------------------------
204
205 async function createHlsJobIfEnabled (user: MUserId, payload: {
206 videoUUID: string
207 resolution: number
208 isPortraitMode?: boolean
209 copyCodecs: boolean
210 }) {
211 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return
212
213 const jobOptions = {
214 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
215 }
216
217 const hlsTranscodingPayload: HLSTranscodingPayload = {
218 type: 'new-resolution-to-hls',
219 videoUUID: payload.videoUUID,
220 resolution: payload.resolution,
221 isPortraitMode: payload.isPortraitMode,
222 copyCodecs: payload.copyCodecs
223 }
224
225 return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
226 }
227
228 async function createLowerResolutionsJobs (
229 video: MVideoFullLight,
230 user: MUserId,
231 videoFileResolution: number,
232 isPortraitMode: boolean
233 ) {
234 // Create transcoding jobs if there are enabled resolutions
235 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
236 logger.info(
237 'Resolutions computed for video %s and origin file resolution of %d.', video.uuid, videoFileResolution,
238 { resolutions: resolutionsEnabled }
239 )
240
241 if (resolutionsEnabled.length === 0) {
242 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
243
244 return false
245 }
246
247 for (const resolution of resolutionsEnabled) {
248 let dataInput: VideoTranscodingPayload
249
250 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED) {
251 // WebTorrent will create subsequent HLS job
252 dataInput = {
253 type: 'new-resolution-to-webtorrent',
254 videoUUID: video.uuid,
255 resolution,
256 isPortraitMode
257 }
258 } else if (CONFIG.TRANSCODING.HLS.ENABLED) {
259 dataInput = {
260 type: 'new-resolution-to-hls',
261 videoUUID: video.uuid,
262 resolution,
263 isPortraitMode,
264 copyCodecs: false
265 }
266 }
267
268 const jobOptions = {
269 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
270 }
271
272 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
273 }
274
275 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })
276
277 return true
278 }