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)
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) {
125 if (video === undefined) return undefined
127 // We generated the HLS playlist, we don't need the webtorrent files anymore if the admin disabled it
128 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
129 for (const file of video.VideoFiles) {
130 await video.removeFile(file)
134 video.VideoFiles = []
137 return publishAndFederateIfNeeded(video)
140 async function onVideoFileOptimizer (
141 videoArg: MVideoWithFile,
142 payload: OptimizeTranscodingPayload,
143 transcodeType: TranscodeOptionsType,
146 if (videoArg === undefined) return undefined
148 // Outside the transaction (IO on disk)
149 const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
151 const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => {
152 // Maybe the video changed in database, refresh it
153 const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t)
154 // Video does not exist anymore
155 if (!videoDatabase) return undefined
157 let videoPublished = false
159 // Generate HLS version of the original file
160 const originalFileHLSPayload = Object.assign({}, payload, {
162 resolution: videoDatabase.getMaxQualityFile().resolution,
163 // If we quick transcoded original file, force transcoding for HLS to avoid some weird playback issues
164 copyCodecs: transcodeType !== 'quick-transcode'
166 await createHlsJobIfEnabled(user, originalFileHLSPayload)
168 const hasNewResolutions = createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode)
170 if (!hasNewResolutions) {
171 // No transcoding to do, it's now published
172 videoPublished = await videoDatabase.publishIfNeededAndSave(t)
175 await federateVideoIfNeeded(videoDatabase, payload.isNewVideo, t)
177 return { videoDatabase, videoPublished }
180 if (payload.isNewVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoDatabase)
181 if (videoPublished) Notifier.Instance.notifyOnVideoPublishedAfterTranscoding(videoDatabase)
184 async function onNewWebTorrentFileResolution (
187 payload?: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload
189 await publishAndFederateIfNeeded(video)
191 await createHlsJobIfEnabled(user, Object.assign({}, payload, { copyCodecs: true }))
194 // ---------------------------------------------------------------------------
197 processVideoTranscoding,
198 onNewWebTorrentFileResolution
201 // ---------------------------------------------------------------------------
203 async function createHlsJobIfEnabled (user: MUserId, payload: {
206 isPortraitMode?: boolean
209 if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return
212 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
215 const hlsTranscodingPayload: HLSTranscodingPayload = {
216 type: 'new-resolution-to-hls',
217 videoUUID: payload.videoUUID,
218 resolution: payload.resolution,
219 isPortraitMode: payload.isPortraitMode,
220 copyCodecs: payload.copyCodecs
223 return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: hlsTranscodingPayload }, jobOptions)
226 async function createLowerResolutionsJobs (
227 video: MVideoFullLight,
229 videoFileResolution: number,
230 isPortraitMode: boolean
232 // Create transcoding jobs if there are enabled resolutions
233 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
235 'Resolutions computed for video %s and origin file resolution of %d.', video.uuid, videoFileResolution,
236 { resolutions: resolutionsEnabled }
239 if (resolutionsEnabled.length === 0) {
240 logger.info('No transcoding jobs created for video %s (no resolutions).', video.uuid)
245 for (const resolution of resolutionsEnabled) {
246 let dataInput: VideoTranscodingPayload
248 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED) {
249 // WebTorrent will create subsequent HLS job
251 type: 'new-resolution-to-webtorrent',
252 videoUUID: video.uuid,
256 } else if (CONFIG.TRANSCODING.HLS.ENABLED) {
258 type: 'new-resolution-to-hls',
259 videoUUID: video.uuid,
267 priority: JOB_PRIORITY.TRANSCODING.NEW_RESOLUTION + await getJobTranscodingPriorityMalus(user)
270 JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }, jobOptions)
273 logger.info('Transcoding jobs created for uuid %s.', video.uuid, { resolutionsEnabled })