]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Safely remove webtorrent 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'
77d7e851
C
3import { JOB_PRIORITY } from '@server/initializers/constants'
4import { getJobTranscodingPriorityMalus, publishAndFederateIfNeeded } from '@server/lib/video'
b5b68755 5import { getVideoFilePath } from '@server/lib/video-paths'
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
C
17import { CONFIG } from '../../../initializers/config'
18import { sequelizeTypescript } from '../../../initializers/database'
3fd3ab2d 19import { VideoModel } from '../../../models/video/video'
8dc8a34e 20import { federateVideoIfNeeded } from '../../activitypub/videos'
cef534ed 21import { Notifier } from '../../notifier'
24516aa2
C
22import {
23 generateHlsPlaylistResolution,
24 mergeAudioVideofile,
25 optimizeOriginalVideofile,
26 transcodeNewWebTorrentResolution
27} from '../../video-transcoding'
b5b68755 28import { JobQueue } from '../job-queue'
77d7e851 29import { UserModel } from '@server/models/account/user'
24516aa2 30
77d7e851
C
31type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
32
33const handlers: { [ id: string ]: HandlerFunction } = {
24516aa2
C
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}
40298b02 50
a0327eed
C
51async function processVideoTranscoding (job: Bull.Job) {
52 const payload = job.data as VideoTranscodingPayload
94a5ff8a
C
53 logger.info('Processing video file in job %d.', job.id)
54
627621c1 55 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
f5028693
C
56 // No video, maybe deleted?
57 if (!video) {
c1e791ba 58 logger.info('Do not process job %d, video does not exist.', job.id)
f5028693
C
59 return undefined
60 }
61
77d7e851
C
62 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
63
24516aa2 64 const handler = handlers[payload.type]
b5b68755 65
24516aa2
C
66 if (!handler) {
67 throw new Error('Cannot find transcoding handler for ' + payload.type)
68 }
b5b68755 69
77d7e851 70 await handler(job, payload, video, user)
24516aa2
C
71
72 return video
73}
09209296 74
24516aa2
C
75// ---------------------------------------------------------------------------
76// Job handlers
77// ---------------------------------------------------------------------------
2186386c 78
24516aa2
C
79async 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 })
536598cf 95
6939cbac 96 await retryTransactionWrapper(onHlsPlaylistGeneration, video, payload.resolution)
24516aa2 97}
2186386c 98
77d7e851
C
99async function handleNewWebTorrentResolutionJob (
100 job: Bull.Job,
101 payload: NewResolutionTranscodingPayload,
102 video: MVideoFullLight,
103 user: MUserId
104) {
24516aa2 105 await transcodeNewWebTorrentResolution(video, payload.resolution, payload.isPortraitMode || false, job)
031094f7 106
77d7e851 107 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
24516aa2
C
108}
109
77d7e851 110async function handleWebTorrentMergeAudioJob (job: Bull.Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
111 await mergeAudioVideofile(video, payload.resolution, job)
112
77d7e851 113 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
40298b02
C
114}
115
77d7e851 116async function handleWebTorrentOptimizeJob (job: Bull.Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
117 const transcodeType = await optimizeOriginalVideofile(video, video.getMaxQualityFile(), job)
118
77d7e851 119 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, transcodeType, user)
24516aa2
C
120}
121
122// ---------------------------------------------------------------------------
123
6939cbac 124async function onHlsPlaylistGeneration (video: MVideoFullLight, resolution: number) {
09209296
C
125 if (video === undefined) return undefined
126
6939cbac
C
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) {
d7a25329
C
131 for (const file of video.VideoFiles) {
132 await video.removeFile(file)
133 await file.destroy()
1b952dd4 134 }
2186386c 135
d7a25329
C
136 video.VideoFiles = []
137 }
94a5ff8a 138
d7a25329
C
139 return publishAndFederateIfNeeded(video)
140}
e8d246d5 141
24516aa2 142async function onVideoFileOptimizer (
236841a1
C
143 videoArg: MVideoWithFile,
144 payload: OptimizeTranscodingPayload,
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
dc133480 153 const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
2186386c 154 // Maybe the video changed in database, refresh it
a1587156 155 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
2186386c
C
156 // Video does not exist anymore
157 if (!videoDatabase) return undefined
158
dc133480
C
159 let videoPublished = false
160
24516aa2 161 // Generate HLS version of the original file
236841a1
C
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 })
77d7e851 168 await createHlsJobIfEnabled(user, originalFileHLSPayload)
d7a25329 169
77d7e851 170 const hasNewResolutions = createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode)
f5028693 171
24516aa2 172 if (!hasNewResolutions) {
2186386c 173 // No transcoding to do, it's now published
d7a25329 174 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
f5028693 175 }
a7977280 176
09209296 177 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
e8d246d5 178
dc133480 179 return { videoDatabase, videoPublished }
2186386c 180 })
e8d246d5 181
5b77537c 182 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
7ccddd7b 183 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
40298b02
C
184}
185
24516aa2
C
186async function onNewWebTorrentFileResolution (
187 video: MVideoUUID,
77d7e851 188 user: MUserId,
24516aa2
C
189 payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
190) {
191 await publishAndFederateIfNeeded(video)
192
77d7e851 193 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true }))
24516aa2
C
194}
195
40298b02
C
196// ---------------------------------------------------------------------------
197
198export {
a0327eed 199 processVideoTranscoding,
24516aa2 200 onNewWebTorrentFileResolution
40298b02 201}
09209296
C
202
203// ---------------------------------------------------------------------------
204
77d7e851
C
205async 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 }
09209296 216
77d7e851
C
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
09209296 223 }
77d7e851
C
224
225 return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
09209296 226}
24516aa2 227
77d7e851
C
228async function createLowerResolutionsJobs (
229 video: MVideoFullLight,
230 user: MUserId,
231 videoFileResolution: number,
232 isPortraitMode: boolean
233) {
24516aa2
C
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
77d7e851
C
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)
24516aa2
C
273 }
274
275 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })
276
277 return true
278}