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: [ ] }
32 `-maxrate ${targetBitrate}`,
33 `-bufsize ${targetBitrate * 2}`
38 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, streamNum }) => {
39 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
43 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
44 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
45 `-maxrate ${targetBitrate}`,
46 `-bufsize ${targetBitrate * 2}`
51 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
52 const probe = await ffprobePromise(input)
54 if (await canDoQuickAudioTranscode(input, probe)) {
55 logger.debug('Copy audio stream %s by AAC encoder.', input)
56 return { copy: true, outputOptions: [] }
59 const parsedAudio = await getAudioStream(input, probe)
61 // We try to reduce the ceiling bitrate by making rough matches of bitrates
62 // Of course this is far from perfect, but it might save some space in the end
64 const audioCodecName = parsedAudio.audioStream['codec_name']
66 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
68 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
70 if (bitrate !== undefined && bitrate !== -1) {
71 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
74 return { outputOptions: [ ] }
77 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
78 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
81 // Used to get and update available encoders
82 class VideoTranscodingProfilesManager {
83 private static instance: VideoTranscodingProfilesManager
85 // 1 === less priority
86 private readonly encodersPriorities = {
87 vod: this.buildDefaultEncodersPriorities(),
88 live: this.buildDefaultEncodersPriorities()
91 private readonly availableEncoders = {
94 default: defaultX264VODOptionsBuilder
97 default: defaultAACOptionsBuilder
100 default: defaultLibFDKAACVODOptionsBuilder
105 default: defaultX264LiveOptionsBuilder
108 default: defaultAACOptionsBuilder
113 private availableProfiles = {
118 private constructor () {
119 this.buildAvailableProfiles()
122 getAvailableEncoders (): AvailableEncoders {
124 available: this.availableEncoders,
127 video: this.getEncodersByPriority('vod', 'video'),
128 audio: this.getEncodersByPriority('vod', 'audio')
131 video: this.getEncodersByPriority('live', 'video'),
132 audio: this.getEncodersByPriority('live', 'audio')
138 getAvailableProfiles (type: 'vod' | 'live') {
139 return this.availableProfiles[type]
142 addProfile (options: {
146 builder: EncoderOptionsBuilder
148 const { type, encoder, profile, builder } = options
150 const encoders = this.availableEncoders[type]
152 if (!encoders[encoder]) encoders[encoder] = {}
153 encoders[encoder][profile] = builder
155 this.buildAvailableProfiles()
158 removeProfile (options: {
163 const { type, encoder, profile } = options
165 delete this.availableEncoders[type][encoder][profile]
166 this.buildAvailableProfiles()
169 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
170 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
172 resetSupportedEncoders()
175 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
176 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
177 .filter(o => o.name !== encoder && o.priority !== priority)
179 resetSupportedEncoders()
182 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
183 return this.encodersPriorities[type][streamType]
185 if (e1.priority > e2.priority) return -1
186 else if (e1.priority === e2.priority) return 0
193 private buildAvailableProfiles () {
194 for (const type of [ 'vod', 'live' ]) {
195 const result = new Set()
197 const encoders = this.availableEncoders[type]
199 for (const encoderName of Object.keys(encoders)) {
200 for (const profile of Object.keys(encoders[encoderName])) {
205 this.availableProfiles[type] = Array.from(result)
208 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
211 private buildDefaultEncodersPriorities () {
214 { name: 'libx264', priority: 100 }
217 // Try the first one, if not available try the second one etc
219 // we favor VBR, if a good AAC encoder is available
220 { name: 'libfdk_aac', priority: 200 },
221 { name: 'aac', priority: 100 }
226 static get Instance () {
227 return this.instance || (this.instance = new this())
231 // ---------------------------------------------------------------------------
234 VideoTranscodingProfilesManager
237 // ---------------------------------------------------------------------------
238 async function buildTargetBitrate (options: {
240 resolution: VideoResolution
243 const { input, resolution, fps } = options
244 const probe = await ffprobePromise(input)
246 const videoStream = await getVideoStreamFromFile(input, probe)
247 if (!videoStream) return undefined
249 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
251 // Don't transcode to an higher bitrate than the original file
252 const fileBitrate = await getVideoFileBitrate(input, probe)
253 return Math.min(targetBitrate, fileBitrate)