2 import { logger } from '@server/helpers/logger'
3 import { getAverageBitrate, getMinLimitBitrate } from '@shared/core-utils'
4 import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams, VideoResolution } from '../../../shared/models/videos'
5 import { buildStreamSuffix, resetSupportedEncoders } from '../../helpers/ffmpeg-utils'
6 import { canDoQuickAudioTranscode, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '../../helpers/ffprobe-utils'
10 * Available encoders and profiles for the transcoding jobs
11 * These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
14 * * https://slhck.info/video/2017/03/01/rate-control.html
15 * * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
18 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
19 const { fps, inputRatio, inputBitrate, resolution } = options
20 if (!fps) return { outputOptions: [ ] }
22 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
28 `-maxrate ${targetBitrate}`,
29 `-bufsize ${targetBitrate * 2}`
34 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
35 const { streamNum, fps, inputBitrate, inputRatio, resolution } = options
37 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
42 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
43 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
44 `-maxrate ${targetBitrate}`,
45 `-bufsize ${targetBitrate * 2}`
50 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
51 const probe = await ffprobePromise(input)
53 if (await canDoQuickAudioTranscode(input, probe)) {
54 logger.debug('Copy audio stream %s by AAC encoder.', input)
55 return { copy: true, outputOptions: [ ] }
58 const parsedAudio = await getAudioStream(input, probe)
60 // We try to reduce the ceiling bitrate by making rough matches of bitrates
61 // Of course this is far from perfect, but it might save some space in the end
63 const audioCodecName = parsedAudio.audioStream['codec_name']
65 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
67 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
70 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
73 return { outputOptions: [ ] }
76 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
77 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
80 // Used to get and update available encoders
81 class VideoTranscodingProfilesManager {
82 private static instance: VideoTranscodingProfilesManager
84 // 1 === less priority
85 private readonly encodersPriorities = {
86 vod: this.buildDefaultEncodersPriorities(),
87 live: this.buildDefaultEncodersPriorities()
90 private readonly availableEncoders = {
93 default: defaultX264VODOptionsBuilder
96 default: defaultAACOptionsBuilder
99 default: defaultLibFDKAACVODOptionsBuilder
104 default: defaultX264LiveOptionsBuilder
107 default: defaultAACOptionsBuilder
112 private availableProfiles = {
117 private constructor () {
118 this.buildAvailableProfiles()
121 getAvailableEncoders (): AvailableEncoders {
123 available: this.availableEncoders,
126 video: this.getEncodersByPriority('vod', 'video'),
127 audio: this.getEncodersByPriority('vod', 'audio')
130 video: this.getEncodersByPriority('live', 'video'),
131 audio: this.getEncodersByPriority('live', 'audio')
137 getAvailableProfiles (type: 'vod' | 'live') {
138 return this.availableProfiles[type]
141 addProfile (options: {
145 builder: EncoderOptionsBuilder
147 const { type, encoder, profile, builder } = options
149 const encoders = this.availableEncoders[type]
151 if (!encoders[encoder]) encoders[encoder] = {}
152 encoders[encoder][profile] = builder
154 this.buildAvailableProfiles()
157 removeProfile (options: {
162 const { type, encoder, profile } = options
164 delete this.availableEncoders[type][encoder][profile]
165 this.buildAvailableProfiles()
168 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
169 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
171 resetSupportedEncoders()
174 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
175 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
176 .filter(o => o.name !== encoder && o.priority !== priority)
178 resetSupportedEncoders()
181 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
182 return this.encodersPriorities[type][streamType]
184 if (e1.priority > e2.priority) return -1
185 else if (e1.priority === e2.priority) return 0
192 private buildAvailableProfiles () {
193 for (const type of [ 'vod', 'live' ]) {
194 const result = new Set()
196 const encoders = this.availableEncoders[type]
198 for (const encoderName of Object.keys(encoders)) {
199 for (const profile of Object.keys(encoders[encoderName])) {
204 this.availableProfiles[type] = Array.from(result)
207 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
210 private buildDefaultEncodersPriorities () {
213 { name: 'libx264', priority: 100 }
216 // Try the first one, if not available try the second one etc
218 // we favor VBR, if a good AAC encoder is available
219 { name: 'libfdk_aac', priority: 200 },
220 { name: 'aac', priority: 100 }
225 static get Instance () {
226 return this.instance || (this.instance = new this())
230 // ---------------------------------------------------------------------------
233 VideoTranscodingProfilesManager
236 // ---------------------------------------------------------------------------
238 function getTargetBitrate (options: {
240 resolution: VideoResolution
244 const { inputBitrate, resolution, ratio, fps } = options
246 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
247 const limit = getMinLimitBitrate({ resolution, fps, ratio })
249 return Math.max(limit, capped)
252 function capBitrate (inputBitrate: number, targetBitrate: number) {
253 if (!inputBitrate) return targetBitrate
255 // Add 30% margin to input bitrate
256 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
258 return Math.min(targetBitrate, inputBitrateWithMargin)