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