1 import { logger } from '@server/helpers/logger'
2 import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
3 import { AvailableEncoders, buildStreamSuffix, EncoderOptionsBuilder } 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 = {
88 { name: 'libx264', priority: 100 }
91 // Try the first one, if not available try the second one etc
93 // we favor VBR, if a good AAC encoder is available
94 { name: 'libfdk_aac', priority: 200 },
95 { name: 'aac', priority: 100 }
99 private readonly availableEncoders = {
102 default: defaultX264VODOptionsBuilder
105 default: defaultAACOptionsBuilder
108 default: defaultLibFDKAACVODOptionsBuilder
113 default: defaultX264LiveOptionsBuilder
116 default: defaultAACOptionsBuilder
121 private constructor () {
125 getAvailableEncoders (): AvailableEncoders {
126 const encodersToTry = {
127 video: this.getEncodersByPriority('video'),
128 audio: this.getEncodersByPriority('audio')
131 return Object.assign({}, this.availableEncoders, { encodersToTry })
134 getAvailableProfiles (type: 'vod' | 'live') {
135 return this.availableEncoders[type]
138 private getEncodersByPriority (type: 'video' | 'audio') {
139 return this.encodersPriorities[type]
141 if (e1.priority > e2.priority) return -1
142 else if (e1.priority === e2.priority) return 0
149 static get Instance () {
150 return this.instance || (this.instance = new this())
154 // ---------------------------------------------------------------------------
157 VideoTranscodingProfilesManager
160 // ---------------------------------------------------------------------------
161 async function buildTargetBitrate (options: {
163 resolution: VideoResolution
166 const { input, resolution, fps } = options
167 const probe = await ffprobePromise(input)
169 const videoStream = await getVideoStreamFromFile(input, probe)
170 if (!videoStream) return undefined
172 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
174 // Don't transcode to an higher bitrate than the original file
175 const fileBitrate = await getVideoFileBitrate(input, probe)
176 return Math.min(targetBitrate, fileBitrate)