2 import { logger } from '@server/helpers/logger'
3 import { getAverageBitrate, getMinLimitBitrate } from '@shared/core-utils'
4 import { buildStreamSuffix, FFmpegCommandWrapper, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '@shared/ffmpeg'
5 import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams, VideoResolution } from '@shared/models'
6 import { canDoQuickAudioTranscode } from './transcoding-quick-transcode'
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 // ---------------------------------------------------------------------------
20 // ---------------------------------------------------------------------------
22 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
23 const { fps, inputRatio, inputBitrate, resolution } = options
25 // TODO: remove in 4.2, fps is not optional anymore
26 if (!fps) return { outputOptions: [ ] }
28 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
32 ...getCommonOutputOptions(targetBitrate),
39 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
40 const { streamNum, fps, inputBitrate, inputRatio, resolution } = options
42 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
46 ...getCommonOutputOptions(targetBitrate, streamNum),
48 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
49 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`
54 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum, canCopyAudio }) => {
55 const probe = await ffprobePromise(input)
57 if (canCopyAudio && await canDoQuickAudioTranscode(input, probe)) {
58 logger.debug('Copy audio stream %s by AAC encoder.', input)
59 return { copy: true, outputOptions: [ ] }
62 const parsedAudio = await getAudioStream(input, probe)
64 // We try to reduce the ceiling bitrate by making rough matches of bitrates
65 // Of course this is far from perfect, but it might save some space in the end
67 const audioCodecName = parsedAudio.audioStream['codec_name']
69 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
71 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
73 // Force stereo as it causes some issues with HLS playback in Chrome
74 const base = [ '-channel_layout', 'stereo' ]
77 return { outputOptions: base.concat([ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ]) }
80 return { outputOptions: base }
83 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
84 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
87 // ---------------------------------------------------------------------------
88 // Profile manager to get and change default profiles
89 // ---------------------------------------------------------------------------
91 class VideoTranscodingProfilesManager {
92 private static instance: VideoTranscodingProfilesManager
94 // 1 === less priority
95 private readonly encodersPriorities = {
96 vod: this.buildDefaultEncodersPriorities(),
97 live: this.buildDefaultEncodersPriorities()
100 private readonly availableEncoders = {
103 default: defaultX264VODOptionsBuilder
106 default: defaultAACOptionsBuilder
109 default: defaultLibFDKAACVODOptionsBuilder
114 default: defaultX264LiveOptionsBuilder
117 default: defaultAACOptionsBuilder
122 private availableProfiles = {
127 private constructor () {
128 this.buildAvailableProfiles()
131 getAvailableEncoders (): AvailableEncoders {
133 available: this.availableEncoders,
136 video: this.getEncodersByPriority('vod', 'video'),
137 audio: this.getEncodersByPriority('vod', 'audio')
140 video: this.getEncodersByPriority('live', 'video'),
141 audio: this.getEncodersByPriority('live', 'audio')
147 getAvailableProfiles (type: 'vod' | 'live') {
148 return this.availableProfiles[type]
151 addProfile (options: {
155 builder: EncoderOptionsBuilder
157 const { type, encoder, profile, builder } = options
159 const encoders = this.availableEncoders[type]
161 if (!encoders[encoder]) encoders[encoder] = {}
162 encoders[encoder][profile] = builder
164 this.buildAvailableProfiles()
167 removeProfile (options: {
172 const { type, encoder, profile } = options
174 delete this.availableEncoders[type][encoder][profile]
175 this.buildAvailableProfiles()
178 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
179 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
181 FFmpegCommandWrapper.resetSupportedEncoders()
184 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
185 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
186 .filter(o => o.name !== encoder && o.priority !== priority)
188 FFmpegCommandWrapper.resetSupportedEncoders()
191 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
192 return this.encodersPriorities[type][streamType]
194 if (e1.priority > e2.priority) return -1
195 else if (e1.priority === e2.priority) return 0
202 private buildAvailableProfiles () {
203 for (const type of [ 'vod', 'live' ]) {
204 const result = new Set()
206 const encoders = this.availableEncoders[type]
208 for (const encoderName of Object.keys(encoders)) {
209 for (const profile of Object.keys(encoders[encoderName])) {
214 this.availableProfiles[type] = Array.from(result)
217 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
220 private buildDefaultEncodersPriorities () {
223 { name: 'libx264', priority: 100 }
226 // Try the first one, if not available try the second one etc
228 // we favor VBR, if a good AAC encoder is available
229 { name: 'libfdk_aac', priority: 200 },
230 { name: 'aac', priority: 100 }
235 static get Instance () {
236 return this.instance || (this.instance = new this())
240 // ---------------------------------------------------------------------------
243 VideoTranscodingProfilesManager
246 // ---------------------------------------------------------------------------
248 function getTargetBitrate (options: {
250 resolution: VideoResolution
254 const { inputBitrate, resolution, ratio, fps } = options
256 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
257 const limit = getMinLimitBitrate({ resolution, fps, ratio })
259 return Math.max(limit, capped)
262 function capBitrate (inputBitrate: number, targetBitrate: number) {
263 if (!inputBitrate) return targetBitrate
265 // Add 30% margin to input bitrate
266 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
268 return Math.min(targetBitrate, inputBitrateWithMargin)
271 function getCommonOutputOptions (targetBitrate: number, streamNum?: number) {
274 `${buildStreamSuffix('-maxrate:v', streamNum)} ${targetBitrate}`,
275 `${buildStreamSuffix('-bufsize:v', streamNum)} ${targetBitrate * 2}`,
277 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
279 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16