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'
5 canDoQuickAudioTranscode,
10 getVideoStreamFromFile
11 } from '../helpers/ffprobe-utils'
12 import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
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
22 // * https://slhck.info/video/2017/03/01/rate-control.html
23 // * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
25 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
26 const targetBitrate = await buildTargetBitrate({ input, resolution, fps })
27 if (!targetBitrate) return { outputOptions: [ ] }
33 `-maxrate ${targetBitrate}`,
34 `-bufsize ${targetBitrate * 2}`
39 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, streamNum }) => {
40 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
45 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
46 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
47 `-maxrate ${targetBitrate}`,
48 `-bufsize ${targetBitrate * 2}`
53 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
54 const probe = await ffprobePromise(input)
56 if (await canDoQuickAudioTranscode(input, probe)) {
57 logger.debug('Copy audio stream %s by AAC encoder.', input)
58 return { copy: true, outputOptions: [ ] }
61 const parsedAudio = await getAudioStream(input, probe)
63 // We try to reduce the ceiling bitrate by making rough matches of bitrates
64 // Of course this is far from perfect, but it might save some space in the end
66 const audioCodecName = parsedAudio.audioStream['codec_name']
68 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
70 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
72 if (bitrate !== undefined && bitrate !== -1) {
73 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
76 return { outputOptions: [ ] }
79 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
80 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
83 // Used to get and update available encoders
84 class VideoTranscodingProfilesManager {
85 private static instance: VideoTranscodingProfilesManager
87 // 1 === less priority
88 private readonly encodersPriorities = {
89 vod: this.buildDefaultEncodersPriorities(),
90 live: this.buildDefaultEncodersPriorities()
93 private readonly availableEncoders = {
96 default: defaultX264VODOptionsBuilder
99 default: defaultAACOptionsBuilder
102 default: defaultLibFDKAACVODOptionsBuilder
107 default: defaultX264LiveOptionsBuilder
110 default: defaultAACOptionsBuilder
115 private availableProfiles = {
120 private constructor () {
121 this.buildAvailableProfiles()
124 getAvailableEncoders (): AvailableEncoders {
126 available: this.availableEncoders,
129 video: this.getEncodersByPriority('vod', 'video'),
130 audio: this.getEncodersByPriority('vod', 'audio')
133 video: this.getEncodersByPriority('live', 'video'),
134 audio: this.getEncodersByPriority('live', 'audio')
140 getAvailableProfiles (type: 'vod' | 'live') {
141 return this.availableProfiles[type]
144 addProfile (options: {
148 builder: EncoderOptionsBuilder
150 const { type, encoder, profile, builder } = options
152 const encoders = this.availableEncoders[type]
154 if (!encoders[encoder]) encoders[encoder] = {}
155 encoders[encoder][profile] = builder
157 this.buildAvailableProfiles()
160 removeProfile (options: {
165 const { type, encoder, profile } = options
167 delete this.availableEncoders[type][encoder][profile]
168 this.buildAvailableProfiles()
171 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
172 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
174 resetSupportedEncoders()
177 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
178 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
179 .filter(o => o.name !== encoder && o.priority !== priority)
181 resetSupportedEncoders()
184 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
185 return this.encodersPriorities[type][streamType]
187 if (e1.priority > e2.priority) return -1
188 else if (e1.priority === e2.priority) return 0
195 private buildAvailableProfiles () {
196 for (const type of [ 'vod', 'live' ]) {
197 const result = new Set()
199 const encoders = this.availableEncoders[type]
201 for (const encoderName of Object.keys(encoders)) {
202 for (const profile of Object.keys(encoders[encoderName])) {
207 this.availableProfiles[type] = Array.from(result)
210 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
213 private buildDefaultEncodersPriorities () {
216 { name: 'libx264', priority: 100 }
219 // Try the first one, if not available try the second one etc
221 // we favor VBR, if a good AAC encoder is available
222 { name: 'libfdk_aac', priority: 200 },
223 { name: 'aac', priority: 100 }
228 static get Instance () {
229 return this.instance || (this.instance = new this())
233 // ---------------------------------------------------------------------------
236 VideoTranscodingProfilesManager
239 // ---------------------------------------------------------------------------
240 async function buildTargetBitrate (options: {
242 resolution: VideoResolution
245 const { input, resolution, fps } = options
246 const probe = await ffprobePromise(input)
248 const videoStream = await getVideoStreamFromFile(input, probe)
249 if (!videoStream) return undefined
251 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
253 // Don't transcode to an higher bitrate than the original file
254 const fileBitrate = await getVideoFileBitrate(input, probe)
255 return Math.min(targetBitrate, fileBitrate)