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, streamNum),
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 })
79 // Force stereo as it causes some issues with HLS playback in Chrome
80 const base = [ '-channel_layout', 'stereo' ]
83 return { outputOptions: base.concat([ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ]) }
86 return { outputOptions: base }
89 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
90 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
93 // ---------------------------------------------------------------------------
94 // Profile manager to get and change default profiles
95 // ---------------------------------------------------------------------------
97 class VideoTranscodingProfilesManager {
98 private static instance: VideoTranscodingProfilesManager
100 // 1 === less priority
101 private readonly encodersPriorities = {
102 vod: this.buildDefaultEncodersPriorities(),
103 live: this.buildDefaultEncodersPriorities()
106 private readonly availableEncoders = {
109 default: defaultX264VODOptionsBuilder
112 default: defaultAACOptionsBuilder
115 default: defaultLibFDKAACVODOptionsBuilder
120 default: defaultX264LiveOptionsBuilder
123 default: defaultAACOptionsBuilder
128 private availableProfiles = {
133 private constructor () {
134 this.buildAvailableProfiles()
137 getAvailableEncoders (): AvailableEncoders {
139 available: this.availableEncoders,
142 video: this.getEncodersByPriority('vod', 'video'),
143 audio: this.getEncodersByPriority('vod', 'audio')
146 video: this.getEncodersByPriority('live', 'video'),
147 audio: this.getEncodersByPriority('live', 'audio')
153 getAvailableProfiles (type: 'vod' | 'live') {
154 return this.availableProfiles[type]
157 addProfile (options: {
161 builder: EncoderOptionsBuilder
163 const { type, encoder, profile, builder } = options
165 const encoders = this.availableEncoders[type]
167 if (!encoders[encoder]) encoders[encoder] = {}
168 encoders[encoder][profile] = builder
170 this.buildAvailableProfiles()
173 removeProfile (options: {
178 const { type, encoder, profile } = options
180 delete this.availableEncoders[type][encoder][profile]
181 this.buildAvailableProfiles()
184 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
185 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
187 resetSupportedEncoders()
190 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
191 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
192 .filter(o => o.name !== encoder && o.priority !== priority)
194 resetSupportedEncoders()
197 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
198 return this.encodersPriorities[type][streamType]
200 if (e1.priority > e2.priority) return -1
201 else if (e1.priority === e2.priority) return 0
208 private buildAvailableProfiles () {
209 for (const type of [ 'vod', 'live' ]) {
210 const result = new Set()
212 const encoders = this.availableEncoders[type]
214 for (const encoderName of Object.keys(encoders)) {
215 for (const profile of Object.keys(encoders[encoderName])) {
220 this.availableProfiles[type] = Array.from(result)
223 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
226 private buildDefaultEncodersPriorities () {
229 { name: 'libx264', priority: 100 }
232 // Try the first one, if not available try the second one etc
234 // we favor VBR, if a good AAC encoder is available
235 { name: 'libfdk_aac', priority: 200 },
236 { name: 'aac', priority: 100 }
241 static get Instance () {
242 return this.instance || (this.instance = new this())
246 // ---------------------------------------------------------------------------
249 VideoTranscodingProfilesManager
252 // ---------------------------------------------------------------------------
254 function getTargetBitrate (options: {
256 resolution: VideoResolution
260 const { inputBitrate, resolution, ratio, fps } = options
262 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
263 const limit = getMinLimitBitrate({ resolution, fps, ratio })
265 return Math.max(limit, capped)
268 function capBitrate (inputBitrate: number, targetBitrate: number) {
269 if (!inputBitrate) return targetBitrate
271 // Add 30% margin to input bitrate
272 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
274 return Math.min(targetBitrate, inputBitrateWithMargin)
277 function getCommonOutputOptions (targetBitrate: number, streamNum?: number) {
280 `${buildStreamSuffix('-maxrate:v', streamNum)} ${targetBitrate}`,
281 `${buildStreamSuffix('-bufsize:v', streamNum)} ${targetBitrate * 2}`,
283 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
285 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16