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'
4 import { canDoQuickAudioTranscode, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '../../helpers/ffprobe-utils'
5 import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
9 * Available encoders and profiles for the transcoding jobs
10 * These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
15 // * https://slhck.info/video/2017/03/01/rate-control.html
16 // * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
18 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ inputBitrate, resolution, fps }) => {
19 const targetBitrate = buildTargetBitrate({ inputBitrate, resolution, fps })
20 if (!targetBitrate) return { outputOptions: [ ] }
26 `-maxrate ${targetBitrate}`,
27 `-bufsize ${targetBitrate * 2}`
32 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, inputBitrate, streamNum }) => {
33 const targetBitrate = buildTargetBitrate({ inputBitrate, resolution, fps })
38 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
39 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
40 `-maxrate ${targetBitrate}`,
41 `-bufsize ${targetBitrate * 2}`
46 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
47 const probe = await ffprobePromise(input)
49 if (await canDoQuickAudioTranscode(input, probe)) {
50 logger.debug('Copy audio stream %s by AAC encoder.', input)
51 return { copy: true, outputOptions: [ ] }
54 const parsedAudio = await getAudioStream(input, probe)
56 // We try to reduce the ceiling bitrate by making rough matches of bitrates
57 // Of course this is far from perfect, but it might save some space in the end
59 const audioCodecName = parsedAudio.audioStream['codec_name']
61 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
63 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
65 if (bitrate !== undefined && bitrate !== -1) {
66 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
69 return { outputOptions: [ ] }
72 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
73 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
76 // Used to get and update available encoders
77 class VideoTranscodingProfilesManager {
78 private static instance: VideoTranscodingProfilesManager
80 // 1 === less priority
81 private readonly encodersPriorities = {
82 vod: this.buildDefaultEncodersPriorities(),
83 live: this.buildDefaultEncodersPriorities()
86 private readonly availableEncoders = {
89 default: defaultX264VODOptionsBuilder
92 default: defaultAACOptionsBuilder
95 default: defaultLibFDKAACVODOptionsBuilder
100 default: defaultX264LiveOptionsBuilder
103 default: defaultAACOptionsBuilder
108 private availableProfiles = {
113 private constructor () {
114 this.buildAvailableProfiles()
117 getAvailableEncoders (): AvailableEncoders {
119 available: this.availableEncoders,
122 video: this.getEncodersByPriority('vod', 'video'),
123 audio: this.getEncodersByPriority('vod', 'audio')
126 video: this.getEncodersByPriority('live', 'video'),
127 audio: this.getEncodersByPriority('live', 'audio')
133 getAvailableProfiles (type: 'vod' | 'live') {
134 return this.availableProfiles[type]
137 addProfile (options: {
141 builder: EncoderOptionsBuilder
143 const { type, encoder, profile, builder } = options
145 const encoders = this.availableEncoders[type]
147 if (!encoders[encoder]) encoders[encoder] = {}
148 encoders[encoder][profile] = builder
150 this.buildAvailableProfiles()
153 removeProfile (options: {
158 const { type, encoder, profile } = options
160 delete this.availableEncoders[type][encoder][profile]
161 this.buildAvailableProfiles()
164 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
165 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
167 resetSupportedEncoders()
170 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
171 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
172 .filter(o => o.name !== encoder && o.priority !== priority)
174 resetSupportedEncoders()
177 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
178 return this.encodersPriorities[type][streamType]
180 if (e1.priority > e2.priority) return -1
181 else if (e1.priority === e2.priority) return 0
188 private buildAvailableProfiles () {
189 for (const type of [ 'vod', 'live' ]) {
190 const result = new Set()
192 const encoders = this.availableEncoders[type]
194 for (const encoderName of Object.keys(encoders)) {
195 for (const profile of Object.keys(encoders[encoderName])) {
200 this.availableProfiles[type] = Array.from(result)
203 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
206 private buildDefaultEncodersPriorities () {
209 { name: 'libx264', priority: 100 }
212 // Try the first one, if not available try the second one etc
214 // we favor VBR, if a good AAC encoder is available
215 { name: 'libfdk_aac', priority: 200 },
216 { name: 'aac', priority: 100 }
221 static get Instance () {
222 return this.instance || (this.instance = new this())
226 // ---------------------------------------------------------------------------
229 VideoTranscodingProfilesManager
232 // ---------------------------------------------------------------------------
234 function buildTargetBitrate (options: {
236 resolution: VideoResolution
239 const { inputBitrate, resolution, fps } = options
241 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
242 if (!inputBitrate) return targetBitrate
244 return Math.min(targetBitrate, inputBitrate)