1 import Bluebird from 'bluebird'
2 import { computeOutputFPS } from '@server/helpers/ffmpeg'
3 import { logger } from '@server/helpers/logger'
4 import { CONFIG } from '@server/initializers/config'
5 import { DEFAULT_AUDIO_RESOLUTION, VIDEO_TRANSCODING_FPS } from '@server/initializers/constants'
6 import { CreateJobArgument, JobQueue } from '@server/lib/job-queue'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { VideoPathManager } from '@server/lib/video-path-manager'
9 import { VideoJobInfoModel } from '@server/models/video/video-job-info'
10 import { MUserId, MVideoFile, MVideoFullLight, MVideoWithFileThumbnail } from '@server/types/models'
11 import { ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream, isAudioFile } from '@shared/ffmpeg'
13 HLSTranscodingPayload,
14 MergeAudioTranscodingPayload,
15 NewWebTorrentResolutionTranscodingPayload,
16 OptimizeTranscodingPayload,
17 VideoTranscodingPayload
18 } from '@shared/models'
19 import { canDoQuickTranscode } from '../../transcoding-quick-transcode'
20 import { computeResolutionsToTranscode } from '../../transcoding-resolutions'
21 import { AbstractJobBuilder } from './abstract-job-builder'
23 export class TranscodingJobQueueBuilder extends AbstractJobBuilder {
25 async createOptimizeOrMergeAudioJobs (options: {
26 video: MVideoFullLight
30 videoFileAlreadyLocked: boolean
32 const { video, videoFile, isNewVideo, user, videoFileAlreadyLocked } = options
34 let mergeOrOptimizePayload: MergeAudioTranscodingPayload | OptimizeTranscodingPayload
35 let nextTranscodingSequentialJobPayloads: (NewWebTorrentResolutionTranscodingPayload | HLSTranscodingPayload)[][] = []
37 const mutexReleaser = videoFileAlreadyLocked
39 : await VideoPathManager.Instance.lockFiles(video.uuid)
42 await VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(video), async videoFilePath => {
43 const probe = await ffprobePromise(videoFilePath)
45 const { resolution } = await getVideoStreamDimensionsInfo(videoFilePath, probe)
46 const hasAudio = await hasAudioStream(videoFilePath, probe)
47 const quickTranscode = await canDoQuickTranscode(videoFilePath, probe)
48 const inputFPS = videoFile.isAudio()
49 ? VIDEO_TRANSCODING_FPS.AUDIO_MERGE // The first transcoding job will transcode to this FPS value
50 : await getVideoStreamFPS(videoFilePath, probe)
52 const maxResolution = await isAudioFile(videoFilePath, probe)
53 ? DEFAULT_AUDIO_RESOLUTION
56 if (CONFIG.TRANSCODING.HLS.ENABLED === true) {
57 nextTranscodingSequentialJobPayloads.push([
58 this.buildHLSJobPayload({
59 deleteWebTorrentFiles: CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false,
61 // We had some issues with a web video quick transcoded while producing a HLS version of it
62 copyCodecs: !quickTranscode,
64 resolution: maxResolution,
65 fps: computeOutputFPS({ inputFPS, resolution: maxResolution }),
66 videoUUID: video.uuid,
72 const lowerResolutionJobPayloads = await this.buildLowerResolutionJobPayloads({
74 inputVideoResolution: maxResolution,
75 inputVideoFPS: inputFPS,
80 nextTranscodingSequentialJobPayloads = [ ...nextTranscodingSequentialJobPayloads, ...lowerResolutionJobPayloads ]
82 const hasChildren = nextTranscodingSequentialJobPayloads.length !== 0
83 mergeOrOptimizePayload = videoFile.isAudio()
84 ? this.buildMergeAudioPayload({ videoUUID: video.uuid, isNewVideo, hasChildren })
85 : this.buildOptimizePayload({ videoUUID: video.uuid, isNewVideo, quickTranscode, hasChildren })
91 const nextTranscodingSequentialJobs = await Bluebird.mapSeries(nextTranscodingSequentialJobPayloads, payloads => {
92 return Bluebird.mapSeries(payloads, payload => {
93 return this.buildTranscodingJob({ payload, user })
97 const transcodingJobBuilderJob: CreateJobArgument = {
98 type: 'transcoding-job-builder',
100 videoUUID: video.uuid,
101 sequentialJobs: nextTranscodingSequentialJobs
105 const mergeOrOptimizeJob = await this.buildTranscodingJob({ payload: mergeOrOptimizePayload, user })
107 await JobQueue.Instance.createSequentialJobFlow(...[ mergeOrOptimizeJob, transcodingJobBuilderJob ])
109 await VideoJobInfoModel.increaseOrCreate(video.uuid, 'pendingTranscode')
112 // ---------------------------------------------------------------------------
114 async createTranscodingJobs (options: {
115 transcodingType: 'hls' | 'webtorrent'
116 video: MVideoFullLight
117 resolutions: number[]
121 const { video, transcodingType, resolutions, isNewVideo } = options
123 const maxResolution = Math.max(...resolutions)
124 const childrenResolutions = resolutions.filter(r => r !== maxResolution)
126 logger.info('Manually creating transcoding jobs for %s.', transcodingType, { childrenResolutions, maxResolution })
128 const { fps: inputFPS } = await video.probeMaxQualityFile()
130 const children = childrenResolutions.map(resolution => {
131 const fps = computeOutputFPS({ inputFPS, resolution })
133 if (transcodingType === 'hls') {
134 return this.buildHLSJobPayload({ videoUUID: video.uuid, resolution, fps, isNewVideo })
137 if (transcodingType === 'webtorrent') {
138 return this.buildWebTorrentJobPayload({ videoUUID: video.uuid, resolution, fps, isNewVideo })
141 throw new Error('Unknown transcoding type')
144 const fps = computeOutputFPS({ inputFPS, resolution: maxResolution })
146 const parent = transcodingType === 'hls'
147 ? this.buildHLSJobPayload({ videoUUID: video.uuid, resolution: maxResolution, fps, isNewVideo })
148 : this.buildWebTorrentJobPayload({ videoUUID: video.uuid, resolution: maxResolution, fps, isNewVideo })
150 // Process the last resolution after the other ones to prevent concurrency issue
151 // Because low resolutions use the biggest one as ffmpeg input
152 await this.createTranscodingJobsWithChildren({ videoUUID: video.uuid, parent, children, user: null })
155 // ---------------------------------------------------------------------------
157 private async createTranscodingJobsWithChildren (options: {
159 parent: (HLSTranscodingPayload | NewWebTorrentResolutionTranscodingPayload)
160 children: (HLSTranscodingPayload | NewWebTorrentResolutionTranscodingPayload)[]
163 const { videoUUID, parent, children, user } = options
165 const parentJob = await this.buildTranscodingJob({ payload: parent, user })
166 const childrenJobs = await Bluebird.mapSeries(children, c => this.buildTranscodingJob({ payload: c, user }))
168 await JobQueue.Instance.createJobWithChildren(parentJob, childrenJobs)
170 await VideoJobInfoModel.increaseOrCreate(videoUUID, 'pendingTranscode', 1 + children.length)
173 private async buildTranscodingJob (options: {
174 payload: VideoTranscodingPayload
175 user: MUserId | null // null means we don't want priority
177 const { user, payload } = options
180 type: 'video-transcoding' as 'video-transcoding',
181 priority: await this.getTranscodingJobPriority({ user, fallback: undefined }),
186 private async buildLowerResolutionJobPayloads (options: {
187 video: MVideoWithFileThumbnail
188 inputVideoResolution: number
189 inputVideoFPS: number
193 const { video, inputVideoResolution, inputVideoFPS, isNewVideo, hasAudio } = options
195 // Create transcoding jobs if there are enabled resolutions
196 const resolutionsEnabled = await Hooks.wrapObject(
197 computeResolutionsToTranscode({ input: inputVideoResolution, type: 'vod', includeInput: false, strictLower: true, hasAudio }),
198 'filter:transcoding.auto.resolutions-to-transcode.result',
202 const sequentialPayloads: (NewWebTorrentResolutionTranscodingPayload | HLSTranscodingPayload)[][] = []
204 for (const resolution of resolutionsEnabled) {
205 const fps = computeOutputFPS({ inputFPS: inputVideoFPS, resolution })
207 if (CONFIG.TRANSCODING.WEBTORRENT.ENABLED) {
208 const payloads: (NewWebTorrentResolutionTranscodingPayload | HLSTranscodingPayload)[] = [
209 this.buildWebTorrentJobPayload({
210 videoUUID: video.uuid,
217 // Create a subsequent job to create HLS resolution that will just copy web video codecs
218 if (CONFIG.TRANSCODING.HLS.ENABLED) {
220 this.buildHLSJobPayload({
221 videoUUID: video.uuid,
230 sequentialPayloads.push(payloads)
231 } else if (CONFIG.TRANSCODING.HLS.ENABLED) {
232 sequentialPayloads.push([
233 this.buildHLSJobPayload({
234 videoUUID: video.uuid,
244 return sequentialPayloads
247 private buildHLSJobPayload (options: {
252 deleteWebTorrentFiles?: boolean // default false
253 copyCodecs?: boolean // default false
254 }): HLSTranscodingPayload {
255 const { videoUUID, resolution, fps, isNewVideo, deleteWebTorrentFiles = false, copyCodecs = false } = options
258 type: 'new-resolution-to-hls',
264 deleteWebTorrentFiles
268 private buildWebTorrentJobPayload (options: {
273 }): NewWebTorrentResolutionTranscodingPayload {
274 const { videoUUID, resolution, fps, isNewVideo } = options
277 type: 'new-resolution-to-webtorrent',
285 private buildMergeAudioPayload (options: {
289 }): MergeAudioTranscodingPayload {
290 const { videoUUID, isNewVideo, hasChildren } = options
293 type: 'merge-audio-to-webtorrent',
294 resolution: DEFAULT_AUDIO_RESOLUTION,
295 fps: VIDEO_TRANSCODING_FPS.AUDIO_MERGE,
302 private buildOptimizePayload (options: {
304 quickTranscode: boolean
307 }): OptimizeTranscodingPayload {
308 const { videoUUID, quickTranscode, isNewVideo, hasChildren } = options
311 type: 'optimize-to-webtorrent',