]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-transcoding.ts
Use a class for youtube-dl
[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'
a6e37eeb 3import { getTranscodingJobPriority, publishAndFederateIfNeeded } from '@server/lib/video'
b5b68755 4import { getVideoFilePath } from '@server/lib/video-paths'
70243d7a 5import { UserModel } from '@server/models/account/user'
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'
24516aa2 29
77d7e851
C
30type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
31
32const handlers: { [ id: string ]: HandlerFunction } = {
24516aa2
C
33 // Deprecated, introduced in 3.1
34 'hls': handleHLSJob,
35 'new-resolution-to-hls': handleHLSJob,
36
37 // Deprecated, introduced in 3.1
38 'new-resolution': handleNewWebTorrentResolutionJob,
39 'new-resolution-to-webtorrent': handleNewWebTorrentResolutionJob,
40
41 // Deprecated, introduced in 3.1
42 'merge-audio': handleWebTorrentMergeAudioJob,
43 'merge-audio-to-webtorrent': handleWebTorrentMergeAudioJob,
44
45 // Deprecated, introduced in 3.1
46 'optimize': handleWebTorrentOptimizeJob,
47 'optimize-to-webtorrent': handleWebTorrentOptimizeJob
48}
40298b02 49
a0327eed
C
50async function processVideoTranscoding (job: Bull.Job) {
51 const payload = job.data as VideoTranscodingPayload
94a5ff8a
C
52 logger.info('Processing video file in job %d.', job.id)
53
627621c1 54 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
f5028693
C
55 // No video, maybe deleted?
56 if (!video) {
c1e791ba 57 logger.info('Do not process job %d, video does not exist.', job.id)
f5028693
C
58 return undefined
59 }
60
77d7e851
C
61 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
62
24516aa2 63 const handler = handlers[payload.type]
b5b68755 64
24516aa2
C
65 if (!handler) {
66 throw new Error('Cannot find transcoding handler for ' + payload.type)
67 }
b5b68755 68
77d7e851 69 await handler(job, payload, video, user)
24516aa2
C
70
71 return video
72}
09209296 73
24516aa2
C
74// ---------------------------------------------------------------------------
75// Job handlers
76// ---------------------------------------------------------------------------
2186386c 77
9129b769 78async function handleHLSJob (job: Bull.Job, payload: HLSTranscodingPayload, video: MVideoFullLight, user: MUser) {
24516aa2
C
79 const videoFileInput = payload.copyCodecs
80 ? video.getWebTorrentFile(payload.resolution)
81 : video.getMaxQualityFile()
82
83 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
84 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
85
86 await generateHlsPlaylistResolution({
87 video,
88 videoInputPath,
89 resolution: payload.resolution,
90 copyCodecs: payload.copyCodecs,
91 isPortraitMode: payload.isPortraitMode || false,
92 job
93 })
536598cf 94
9129b769 95 await retryTransactionWrapper(onHlsPlaylistGeneration, video, user, payload)
24516aa2 96}
2186386c 97
77d7e851
C
98async function handleNewWebTorrentResolutionJob (
99 job: Bull.Job,
100 payload: NewResolutionTranscodingPayload,
101 video: MVideoFullLight,
102 user: MUserId
103) {
24516aa2 104 await transcodeNewWebTorrentResolution(video, payload.resolution, payload.isPortraitMode || false, job)
031094f7 105
77d7e851 106 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
24516aa2
C
107}
108
77d7e851 109async function handleWebTorrentMergeAudioJob (job: Bull.Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
110 await mergeAudioVideofile(video, payload.resolution, job)
111
9129b769 112 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, 'video', user)
40298b02
C
113}
114
77d7e851 115async function handleWebTorrentOptimizeJob (job: Bull.Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
24516aa2
C
116 const transcodeType = await optimizeOriginalVideofile(video, video.getMaxQualityFile(), job)
117
77d7e851 118 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, transcodeType, user)
24516aa2
C
119}
120
121// ---------------------------------------------------------------------------
122
9129b769 123async function onHlsPlaylistGeneration (video: MVideoFullLight, user: MUser, payload: HLSTranscodingPayload) {
09209296
C
124 if (video === undefined) return undefined
125
9129b769
C
126 if (payload.isMaxQuality && CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
127 // Remove webtorrent files if not enabled
d7a25329
C
128 for (const file of video.VideoFiles) {
129 await video.removeFile(file)
90a8bd30 130 await file.removeTorrent()
d7a25329 131 await file.destroy()
1b952dd4 132 }
2186386c 133
d7a25329 134 video.VideoFiles = []
9129b769
C
135
136 // Create HLS new resolution jobs
137 await createLowerResolutionsJobs(video, user, payload.resolution, payload.isPortraitMode, 'hls')
d7a25329 138 }
94a5ff8a 139
d7a25329
C
140 return publishAndFederateIfNeeded(video)
141}
e8d246d5 142
24516aa2 143async function onVideoFileOptimizer (
236841a1 144 videoArg: MVideoWithFile,
9129b769 145 payload: OptimizeTranscodingPayload | MergeAudioTranscodingPayload,
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
9129b769
C
167 copyCodecs: transcodeType !== 'quick-transcode',
168 isMaxQuality: true
236841a1 169 })
70243d7a 170 const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
d7a25329 171
9129b769 172 const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode, 'webtorrent')
f5028693 173
70243d7a 174 if (!hasHls && !hasNewResolutions) {
2186386c 175 // No transcoding to do, it's now published
d7a25329 176 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
f5028693 177 }
a7977280 178
09209296 179 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
e8d246d5 180
dc133480 181 return { videoDatabase, videoPublished }
2186386c 182 })
e8d246d5 183
5b77537c 184 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
7ccddd7b 185 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
40298b02
C
186}
187
24516aa2
C
188async function onNewWebTorrentFileResolution (
189 video: MVideoUUID,
77d7e851 190 user: MUserId,
69eddafb 191 payload: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
24516aa2
C
192) {
193 await publishAndFederateIfNeeded(video)
194
9129b769 195 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true, isMaxQuality: false }))
24516aa2
C
196}
197
40298b02
C
198// ---------------------------------------------------------------------------
199
200export {
a0327eed 201 processVideoTranscoding,
24516aa2 202 onNewWebTorrentFileResolution
40298b02 203}
09209296
C
204
205// ---------------------------------------------------------------------------
206
77d7e851
C
207async function createHlsJobIfEnabled (user: MUserId, payload: {
208 videoUUID: string
209 resolution: number
210 isPortraitMode?: boolean
211 copyCodecs: boolean
9129b769 212 isMaxQuality: boolean
77d7e851 213}) {
70243d7a 214 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false
77d7e851
C
215
216 const jobOptions = {
a6e37eeb 217 priority: await getTranscodingJobPriority(user)
77d7e851 218 }
09209296 219
77d7e851
C
220 const hlsTranscodingPayload: HLSTranscodingPayload = {
221 type: 'new-resolution-to-hls',
222 videoUUID: payload.videoUUID,
223 resolution: payload.resolution,
224 isPortraitMode: payload.isPortraitMode,
9129b769
C
225 copyCodecs: payload.copyCodecs,
226 isMaxQuality: payload.isMaxQuality
09209296 227 }
77d7e851 228
70243d7a
C
229 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
230
231 return true
09209296 232}
24516aa2 233
77d7e851
C
234async function createLowerResolutionsJobs (
235 video: MVideoFullLight,
236 user: MUserId,
237 videoFileResolution: number,
9129b769
C
238 isPortraitMode: boolean,
239 type: 'hls' | 'webtorrent'
77d7e851 240) {
24516aa2
C
241 // Create transcoding jobs if there are enabled resolutions
242 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
70243d7a 243 const resolutionCreated: number[] = []
24516aa2
C
244
245 for (const resolution of resolutionsEnabled) {
246 let dataInput: VideoTranscodingPayload
247
9129b769 248 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED && type === 'webtorrent') {
24516aa2
C
249 // WebTorrent will create subsequent HLS job
250 dataInput = {
251 type: 'new-resolution-to-webtorrent',
252 videoUUID: video.uuid,
253 resolution,
254 isPortraitMode
255 }
9129b769
C
256 }
257
258 if (CONFIG.TRANSCODING.HLS.ENABLED && type === 'hls') {
24516aa2
C
259 dataInput = {
260 type: 'new-resolution-to-hls',
261 videoUUID: video.uuid,
262 resolution,
263 isPortraitMode,
9129b769
C
264 copyCodecs: false,
265 isMaxQuality: false
24516aa2
C
266 }
267 }
268
70243d7a
C
269 if (!dataInput) continue
270
271 resolutionCreated.push(resolution)
272
77d7e851 273 const jobOptions = {
a6e37eeb 274 priority: await getTranscodingJobPriority(user)
77d7e851
C
275 }
276
277 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
24516aa2
C
278 }
279
70243d7a
C
280 if (resolutionCreated.length === 0) {
281 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
282
283 return false
284 }
285
286 logger.info(
287 'New resolutions %s transcoding jobs created for video %s and origin file resolution of %d.', type, video.uuid, videoFileResolution,
288 { resolutionCreated }
289 )
24516aa2
C
290
291 return true
292}