1 import { logger } from '@server/helpers/logger'
2 import { AvailableEncoders, EncoderOptionsBuilder, getTargetBitrate, VideoResolution } from '../../shared/models/videos'
3 import { buildStreamSuffix, resetSupportedEncoders } from '../helpers/ffmpeg-utils'
5 canDoQuickAudioTranscode,
10 getVideoStreamFromFile
11 } from '../helpers/ffprobe-utils'
12 import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
16 * Available encoders and profiles for the transcoding jobs
17 * These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
22 // * https://slhck.info/video/2017/03/01/rate-control.html
23 // * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
25 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
26 const targetBitrate = await buildTargetBitrate({ input, resolution, fps })
27 if (!targetBitrate) return { inputOptions: [ ], outputOptions: [ ] }
34 `-maxrate ${targetBitrate}`,
35 `-bufsize ${targetBitrate * 2}`
40 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, streamNum }) => {
41 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
47 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
48 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
49 `-maxrate ${targetBitrate}`,
50 `-bufsize ${targetBitrate * 2}`
55 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
56 const probe = await ffprobePromise(input)
58 if (await canDoQuickAudioTranscode(input, probe)) {
59 logger.debug('Copy audio stream %s by AAC encoder.', input)
60 return { copy: true, inputOptions: [ ], outputOptions: [ ] }
63 const parsedAudio = await getAudioStream(input, probe)
65 // We try to reduce the ceiling bitrate by making rough matches of bitrates
66 // Of course this is far from perfect, but it might save some space in the end
68 const audioCodecName = parsedAudio.audioStream['codec_name']
70 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
72 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
74 if (bitrate !== undefined && bitrate !== -1) {
75 return { inputOptions: [ ], outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
78 return { inputOptions: [ ], outputOptions: [ ] }
81 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
82 return { inputOptions: [ ], outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
85 // Used to get and update available encoders
86 class VideoTranscodingProfilesManager {
87 private static instance: VideoTranscodingProfilesManager
89 // 1 === less priority
90 private readonly encodersPriorities = {
91 vod: this.buildDefaultEncodersPriorities(),
92 live: this.buildDefaultEncodersPriorities()
95 private readonly availableEncoders = {
98 default: defaultX264VODOptionsBuilder
101 default: defaultAACOptionsBuilder
104 default: defaultLibFDKAACVODOptionsBuilder
109 default: defaultX264LiveOptionsBuilder
112 default: defaultAACOptionsBuilder
117 private availableProfiles = {
122 private constructor () {
123 this.buildAvailableProfiles()
126 getAvailableEncoders (): AvailableEncoders {
128 available: this.availableEncoders,
131 video: this.getEncodersByPriority('vod', 'video'),
132 audio: this.getEncodersByPriority('vod', 'audio')
135 video: this.getEncodersByPriority('live', 'video'),
136 audio: this.getEncodersByPriority('live', 'audio')
142 getAvailableProfiles (type: 'vod' | 'live') {
143 return this.availableProfiles[type]
146 addProfile (options: {
150 builder: EncoderOptionsBuilder
152 const { type, encoder, profile, builder } = options
154 const encoders = this.availableEncoders[type]
156 if (!encoders[encoder]) encoders[encoder] = {}
157 encoders[encoder][profile] = builder
159 this.buildAvailableProfiles()
162 removeProfile (options: {
167 const { type, encoder, profile } = options
169 delete this.availableEncoders[type][encoder][profile]
170 this.buildAvailableProfiles()
173 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
174 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
176 resetSupportedEncoders()
179 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
180 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
181 .filter(o => o.name !== encoder && o.priority !== priority)
183 resetSupportedEncoders()
186 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
187 return this.encodersPriorities[type][streamType]
189 if (e1.priority > e2.priority) return -1
190 else if (e1.priority === e2.priority) return 0
197 private buildAvailableProfiles () {
198 for (const type of [ 'vod', 'live' ]) {
199 const result = new Set()
201 const encoders = this.availableEncoders[type]
203 for (const encoderName of Object.keys(encoders)) {
204 for (const profile of Object.keys(encoders[encoderName])) {
209 this.availableProfiles[type] = Array.from(result)
212 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
215 private buildDefaultEncodersPriorities () {
218 { name: 'libx264', priority: 100 }
221 // Try the first one, if not available try the second one etc
223 // we favor VBR, if a good AAC encoder is available
224 { name: 'libfdk_aac', priority: 200 },
225 { name: 'aac', priority: 100 }
230 static get Instance () {
231 return this.instance || (this.instance = new this())
235 // ---------------------------------------------------------------------------
238 VideoTranscodingProfilesManager
241 // ---------------------------------------------------------------------------
242 async function buildTargetBitrate (options: {
244 resolution: VideoResolution
247 const { input, resolution, fps } = options
248 const probe = await ffprobePromise(input)
250 const videoStream = await getVideoStreamFromFile(input, probe)
251 if (!videoStream) return undefined
253 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
255 // Don't transcode to an higher bitrate than the original file
256 const fileBitrate = await getVideoFileBitrate(input, probe)
257 return Math.min(targetBitrate, fileBitrate)