]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - 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
1import * as Bull from 'bull'
2import { TranscodeOptionsType } from '@server/helpers/ffmpeg-utils'
3import { JOB_PRIORITY } from '@server/initializers/constants'
4import { getJobTranscodingPriorityMalus, publishAndFederateIfNeeded } from '@server/lib/video'
5import { getVideoFilePath } from '@server/lib/video-paths'
6import { MUser, MUserId, MVideoFullLight, MVideoUUID, MVideoWithFile } from '@server/types/models'
7import {
8 HLSTranscodingPayload,
9 MergeAudioTranscodingPayload,
10 NewResolutionTranscodingPayload,
11 OptimizeTranscodingPayload,
12 VideoTranscodingPayload
13} from '../../../../shared'
14import { retryTransactionWrapper } from '../../../helpers/database-utils'
15import { computeResolutionsToTranscode } from '../../../helpers/ffprobe-utils'
16import { logger } from '../../../helpers/logger'
17import { CONFIG } from '../../../initializers/config'
18import { sequelizeTypescript } from '../../../initializers/database'
19import { VideoModel } from '../../../models/video/video'
20import { federateVideoIfNeeded } from '../../activitypub/videos'
21import { Notifier } from '../../notifier'
22import {
23 generateHlsPlaylistResolution,
24 mergeAudioVideofile,
25 optimizeOriginalVideofile,
26 transcodeNewWebTorrentResolution
27} from '../../video-transcoding'
28import { JobQueue } from '../job-queue'
29import { UserModel } from '@server/models/account/user'
30
31type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
32
33const 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
51async 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
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 })
95
96 await retryTransactionWrapper(onHlsPlaylistGeneration, video, payload.resolution)
97}
98
99async 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
110async 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
116async 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
124async 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 video.removeTorrent(file)
134 await file.destroy()
135 }
136
137 video.VideoFiles = []
138 }
139
140 return publishAndFederateIfNeeded(video)
141}
142
143async function onVideoFileOptimizer (
144 videoArg: MVideoWithFile,
145 payload: OptimizeTranscodingPayload,
146 transcodeType: TranscodeOptionsType,
147 user: MUserId
148) {
149 if (videoArg === undefined) return undefined
150
151 // Outside the transaction (IO on disk)
152 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
153
154 const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
155 // Maybe the video changed in database, refresh it
156 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
157 // Video does not exist anymore
158 if (!videoDatabase) return undefined
159
160 let videoPublished = false
161
162 // Generate HLS version of the original file
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 })
169 await createHlsJobIfEnabled(user, originalFileHLSPayload)
170
171 const hasNewResolutions = createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode)
172
173 if (!hasNewResolutions) {
174 // No transcoding to do, it's now published
175 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
176 }
177
178 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
179
180 return { videoDatabase, videoPublished }
181 })
182
183 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
184 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
185}
186
187async function onNewWebTorrentFileResolution (
188 video: MVideoUUID,
189 user: MUserId,
190 payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
191) {
192 await publishAndFederateIfNeeded(video)
193
194 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true }))
195}
196
197// ---------------------------------------------------------------------------
198
199export {
200 processVideoTranscoding,
201 onNewWebTorrentFileResolution
202}
203
204// ---------------------------------------------------------------------------
205
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 }
217
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
224 }
225
226 return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
227}
228
229async function createLowerResolutionsJobs (
230 video: MVideoFullLight,
231 user: MUserId,
232 videoFileResolution: number,
233 isPortraitMode: boolean
234) {
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
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)
274 }
275
276 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })
277
278 return true
279}