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'
7 canDoQuickAudioTranscode,
11 resetSupportedEncoders
12 } from '../../helpers/ffmpeg'
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
20 * * https://slhck.info/video/2017/03/01/rate-control.html
21 * * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
24 // ---------------------------------------------------------------------------
26 // ---------------------------------------------------------------------------
28 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
29 const { fps, inputRatio, inputBitrate, resolution } = options
31 // TODO: remove in 4.2, fps is not optional anymore
32 if (!fps) return { outputOptions: [ ] }
34 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
38 ...getCommonOutputOptions(targetBitrate),
45 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
46 const { streamNum, fps, inputBitrate, inputRatio, resolution } = options
48 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
52 ...getCommonOutputOptions(targetBitrate),
54 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
55 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`
60 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum, canCopyAudio }) => {
61 const probe = await ffprobePromise(input)
63 if (canCopyAudio && await canDoQuickAudioTranscode(input, probe)) {
64 logger.debug('Copy audio stream %s by AAC encoder.', input)
65 return { copy: true, outputOptions: [ ] }
68 const parsedAudio = await getAudioStream(input, probe)
70 // We try to reduce the ceiling bitrate by making rough matches of bitrates
71 // Of course this is far from perfect, but it might save some space in the end
73 const audioCodecName = parsedAudio.audioStream['codec_name']
75 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
77 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
80 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
83 return { outputOptions: [ ] }
86 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
87 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
90 // ---------------------------------------------------------------------------
91 // Profile manager to get and change default profiles
92 // ---------------------------------------------------------------------------
94 class VideoTranscodingProfilesManager {
95 private static instance: VideoTranscodingProfilesManager
97 // 1 === less priority
98 private readonly encodersPriorities = {
99 vod: this.buildDefaultEncodersPriorities(),
100 live: this.buildDefaultEncodersPriorities()
103 private readonly availableEncoders = {
106 default: defaultX264VODOptionsBuilder
109 default: defaultAACOptionsBuilder
112 default: defaultLibFDKAACVODOptionsBuilder
117 default: defaultX264LiveOptionsBuilder
120 default: defaultAACOptionsBuilder
125 private availableProfiles = {
130 private constructor () {
131 this.buildAvailableProfiles()
134 getAvailableEncoders (): AvailableEncoders {
136 available: this.availableEncoders,
139 video: this.getEncodersByPriority('vod', 'video'),
140 audio: this.getEncodersByPriority('vod', 'audio')
143 video: this.getEncodersByPriority('live', 'video'),
144 audio: this.getEncodersByPriority('live', 'audio')
150 getAvailableProfiles (type: 'vod' | 'live') {
151 return this.availableProfiles[type]
154 addProfile (options: {
158 builder: EncoderOptionsBuilder
160 const { type, encoder, profile, builder } = options
162 const encoders = this.availableEncoders[type]
164 if (!encoders[encoder]) encoders[encoder] = {}
165 encoders[encoder][profile] = builder
167 this.buildAvailableProfiles()
170 removeProfile (options: {
175 const { type, encoder, profile } = options
177 delete this.availableEncoders[type][encoder][profile]
178 this.buildAvailableProfiles()
181 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
182 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
184 resetSupportedEncoders()
187 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
188 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
189 .filter(o => o.name !== encoder && o.priority !== priority)
191 resetSupportedEncoders()
194 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
195 return this.encodersPriorities[type][streamType]
197 if (e1.priority > e2.priority) return -1
198 else if (e1.priority === e2.priority) return 0
205 private buildAvailableProfiles () {
206 for (const type of [ 'vod', 'live' ]) {
207 const result = new Set()
209 const encoders = this.availableEncoders[type]
211 for (const encoderName of Object.keys(encoders)) {
212 for (const profile of Object.keys(encoders[encoderName])) {
217 this.availableProfiles[type] = Array.from(result)
220 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
223 private buildDefaultEncodersPriorities () {
226 { name: 'libx264', priority: 100 }
229 // Try the first one, if not available try the second one etc
231 // we favor VBR, if a good AAC encoder is available
232 { name: 'libfdk_aac', priority: 200 },
233 { name: 'aac', priority: 100 }
238 static get Instance () {
239 return this.instance || (this.instance = new this())
243 // ---------------------------------------------------------------------------
246 VideoTranscodingProfilesManager
249 // ---------------------------------------------------------------------------
251 function getTargetBitrate (options: {
253 resolution: VideoResolution
257 const { inputBitrate, resolution, ratio, fps } = options
259 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
260 const limit = getMinLimitBitrate({ resolution, fps, ratio })
262 return Math.max(limit, capped)
265 function capBitrate (inputBitrate: number, targetBitrate: number) {
266 if (!inputBitrate) return targetBitrate
268 // Add 30% margin to input bitrate
269 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
271 return Math.min(targetBitrate, inputBitrateWithMargin)
274 function getCommonOutputOptions (targetBitrate: number) {
277 `-maxrate ${targetBitrate}`,
278 `-bufsize ${targetBitrate * 2}`,
280 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
282 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16