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'
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'
23 generateHlsPlaylistResolution,
25 optimizeOriginalVideofile,
26 transcodeNewWebTorrentResolution
27 } from '../../video-transcoding'
28 import { JobQueue } from '../job-queue'
29 import { UserModel } from '@server/models/account/user'
31 type HandlerFunction = (job: Bull.Job, payload: VideoTranscodingPayload, video: MVideoFullLight, user: MUser) => Promise<any>
33 const handlers: { [ id: string ]: HandlerFunction } = {
34 // Deprecated, introduced in 3.1
36 'new-resolution-to-hls': handleHLSJob,
38 // Deprecated, introduced in 3.1
39 'new-resolution': handleNewWebTorrentResolutionJob,
40 'new-resolution-to-webtorrent': handleNewWebTorrentResolutionJob,
42 // Deprecated, introduced in 3.1
43 'merge-audio': handleWebTorrentMergeAudioJob,
44 'merge-audio-to-webtorrent': handleWebTorrentMergeAudioJob,
46 // Deprecated, introduced in 3.1
47 'optimize': handleWebTorrentOptimizeJob,
48 'optimize-to-webtorrent': handleWebTorrentOptimizeJob
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)
55 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
56 // No video, maybe deleted?
58 logger.info('Do not process job %d, video does not exist.', job.id)
62 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
64 const handler = handlers[payload.type]
67 throw new Error('Cannot find transcoding handler for ' + payload.type)
70 await handler(job, payload, video, user)
75 // ---------------------------------------------------------------------------
77 // ---------------------------------------------------------------------------
79 async function handleHLSJob (job: Bull.Job, payload: HLSTranscodingPayload, video: MVideoFullLight) {
80 const videoFileInput = payload.copyCodecs
81 ? video.getWebTorrentFile(payload.resolution)
82 : video.getMaxQualityFile()
84 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
85 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
87 await generateHlsPlaylistResolution({
90 resolution: payload.resolution,
91 copyCodecs: payload.copyCodecs,
92 isPortraitMode: payload.isPortraitMode || false,
96 await retryTransactionWrapper(onHlsPlaylistGeneration, video, payload.resolution)
99 async function handleNewWebTorrentResolutionJob (
101 payload: NewResolutionTranscodingPayload,
102 video: MVideoFullLight,
105 await transcodeNewWebTorrentResolution(video, payload.resolution, payload.isPortraitMode || false, job)
107 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
110 async function handleWebTorrentMergeAudioJob (job: Bull.Job, payload: MergeAudioTranscodingPayload, video: MVideoFullLight, user: MUserId) {
111 await mergeAudioVideofile(video, payload.resolution, job)
113 await retryTransactionWrapper(onNewWebTorrentFileResolution, video, user, payload)
116 async function handleWebTorrentOptimizeJob (job: Bull.Job, payload: OptimizeTranscodingPayload, video: MVideoFullLight, user: MUserId) {
117 const transcodeType = await optimizeOriginalVideofile(video, video.getMaxQualityFile(), job)
119 await retryTransactionWrapper(onVideoFileOptimizer, video, payload, transcodeType, user)
122 // ---------------------------------------------------------------------------
124 async function onHlsPlaylistGeneration (video: MVideoFullLight, resolution: number) {
125 if (video === undefined) return undefined
127 const maxQualityFile = video.getMaxQualityFile()
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)
137 video.VideoFiles = []
140 return publishAndFederateIfNeeded(video)
143 async function onVideoFileOptimizer (
144 videoArg: MVideoWithFile,
145 payload: OptimizeTranscodingPayload,
146 transcodeType: TranscodeOptionsType,
149 if (videoArg === undefined) return undefined
151 // Outside the transaction (IO on disk)
152 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
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
160 let videoPublished = false
162 // Generate HLS version of the original file
163 const originalFileHLSPayload = Object.assign({}, payload, {
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'
169 await createHlsJobIfEnabled(user, originalFileHLSPayload)
171 const hasNewResolutions = createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode)
173 if (!hasNewResolutions) {
174 // No transcoding to do, it's now published
175 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
178 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
180 return { videoDatabase, videoPublished }
183 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
184 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
187 async function onNewWebTorrentFileResolution (
190 payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
192 await publishAndFederateIfNeeded(video)
194 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true }))
197 // ---------------------------------------------------------------------------
200 processVideoTranscoding,
201 onNewWebTorrentFileResolution
204 // ---------------------------------------------------------------------------
206 async function createHlsJobIfEnabled (user: MUserId, payload: {
209 isPortraitMode?: boolean
212 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return
215 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
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
226 return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
229 async function createLowerResolutionsJobs (
230 video: MVideoFullLight,
232 videoFileResolution: number,
233 isPortraitMode: boolean
235 // Create transcoding jobs if there are enabled resolutions
236 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
238 'Resolutions computed for video %s and origin file resolution of %d.', video.uuid, videoFileResolution,
239 { resolutions: resolutionsEnabled }
242 if (resolutionsEnabled.length === 0) {
243 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
248 for (const resolution of resolutionsEnabled) {
249 let dataInput: VideoTranscodingPayload
251 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED) {
252 // WebTorrent will create subsequent HLS job
254 type: 'new-resolution-to-webtorrent',
255 videoUUID: video.uuid,
259 } else if (CONFIG.TRANSCODING.HLS.ENABLED) {
261 type: 'new-resolution-to-hls',
262 videoUUID: video.uuid,
270 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
273 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
276 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })