]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/transcoding/default-transcoding-profiles.ts
Merge branch 'release/4.3.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / transcoding / default-transcoding-profiles.ts
CommitLineData
67eeec8b 1
6b67897e 2import { logger } from '@server/helpers/logger'
67eeec8b
C
3import { getAverageBitrate, getMinLimitBitrate } from '@shared/core-utils'
4import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams, VideoResolution } from '../../../shared/models/videos'
c729caf6
C
5import {
6 buildStreamSuffix,
7 canDoQuickAudioTranscode,
8 ffprobePromise,
9 getAudioStream,
10 getMaxAudioBitrate,
11 resetSupportedEncoders
12} from '../../helpers/ffmpeg'
5a547f69 13
6b67897e
C
14/**
15 *
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
18 *
679c12e6
C
19 * Resources:
20 * * https://slhck.info/video/2017/03/01/rate-control.html
21 * * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
6b67897e 22 */
5a547f69 23
c729caf6
C
24// ---------------------------------------------------------------------------
25// Default builders
26// ---------------------------------------------------------------------------
27
98ab5dc8 28const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
67eeec8b 29 const { fps, inputRatio, inputBitrate, resolution } = options
c729caf6
C
30
31 // TODO: remove in 4.2, fps is not optional anymore
679c12e6 32 if (!fps) return { outputOptions: [ ] }
5a547f69 33
67eeec8b 34 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
5a547f69
C
35
36 return {
37 outputOptions: [
14857212
C
38 ...getCommonOutputOptions(targetBitrate),
39
40 `-r ${fps}`
5a547f69
C
41 ]
42 }
43}
44
98ab5dc8 45const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
67eeec8b 46 const { streamNum, fps, inputBitrate, inputRatio, resolution } = options
679c12e6 47
67eeec8b 48 const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })
5a547f69
C
49
50 return {
51 outputOptions: [
7f529402 52 ...getCommonOutputOptions(targetBitrate, streamNum),
14857212 53
884d2c39 54 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
14857212 55 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`
5a547f69
C
56 ]
57 }
58}
59
c729caf6 60const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum, canCopyAudio }) => {
6b67897e
C
61 const probe = await ffprobePromise(input)
62
c729caf6 63 if (canCopyAudio && await canDoQuickAudioTranscode(input, probe)) {
6b67897e 64 logger.debug('Copy audio stream %s by AAC encoder.', input)
a60696ab 65 return { copy: true, outputOptions: [ ] }
6b67897e
C
66 }
67
68 const parsedAudio = await getAudioStream(input, probe)
5a547f69
C
69
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
72
73 const audioCodecName = parsedAudio.audioStream['codec_name']
74
75 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
76
6b67897e
C
77 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
78
4fd6dcfb
C
79 // Force stereo as it causes some issues with HLS playback in Chrome
80 const base = [ '-channel_layout', 'stereo' ]
81
5ac64497 82 if (bitrate !== -1) {
4fd6dcfb 83 return { outputOptions: base.concat([ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ]) }
5a547f69
C
84 }
85
4fd6dcfb 86 return { outputOptions: base }
5a547f69
C
87}
88
89const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
a60696ab 90 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
5a547f69
C
91}
92
c729caf6
C
93// ---------------------------------------------------------------------------
94// Profile manager to get and change default profiles
95// ---------------------------------------------------------------------------
96
529b3752
C
97class VideoTranscodingProfilesManager {
98 private static instance: VideoTranscodingProfilesManager
99
100 // 1 === less priority
101 private readonly encodersPriorities = {
1896bca0
C
102 vod: this.buildDefaultEncodersPriorities(),
103 live: this.buildDefaultEncodersPriorities()
529b3752
C
104 }
105
106 private readonly availableEncoders = {
107 vod: {
108 libx264: {
109 default: defaultX264VODOptionsBuilder
110 },
111 aac: {
112 default: defaultAACOptionsBuilder
113 },
114 libfdk_aac: {
115 default: defaultLibFDKAACVODOptionsBuilder
116 }
5a547f69 117 },
529b3752
C
118 live: {
119 libx264: {
120 default: defaultX264LiveOptionsBuilder
121 },
122 aac: {
123 default: defaultAACOptionsBuilder
124 }
5a547f69 125 }
529b3752
C
126 }
127
1896bca0
C
128 private availableProfiles = {
129 vod: [] as string[],
130 live: [] as string[]
131 }
529b3752 132
1896bca0
C
133 private constructor () {
134 this.buildAvailableProfiles()
529b3752
C
135 }
136
137 getAvailableEncoders (): AvailableEncoders {
1896bca0
C
138 return {
139 available: this.availableEncoders,
140 encodersToTry: {
141 vod: {
142 video: this.getEncodersByPriority('vod', 'video'),
143 audio: this.getEncodersByPriority('vod', 'audio')
144 },
145 live: {
146 video: this.getEncodersByPriority('live', 'video'),
147 audio: this.getEncodersByPriority('live', 'audio')
148 }
149 }
5a547f69 150 }
529b3752
C
151 }
152
153 getAvailableProfiles (type: 'vod' | 'live') {
1896bca0
C
154 return this.availableProfiles[type]
155 }
156
157 addProfile (options: {
158 type: 'vod' | 'live'
159 encoder: string
160 profile: string
161 builder: EncoderOptionsBuilder
162 }) {
163 const { type, encoder, profile, builder } = options
164
165 const encoders = this.availableEncoders[type]
166
167 if (!encoders[encoder]) encoders[encoder] = {}
168 encoders[encoder][profile] = builder
169
170 this.buildAvailableProfiles()
171 }
172
173 removeProfile (options: {
174 type: 'vod' | 'live'
175 encoder: string
176 profile: string
177 }) {
178 const { type, encoder, profile } = options
179
180 delete this.availableEncoders[type][encoder][profile]
181 this.buildAvailableProfiles()
529b3752
C
182 }
183
1896bca0
C
184 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
185 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
186
187 resetSupportedEncoders()
188 }
189
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)
193
194 resetSupportedEncoders()
195 }
196
197 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
198 return this.encodersPriorities[type][streamType]
529b3752
C
199 .sort((e1, e2) => {
200 if (e1.priority > e2.priority) return -1
201 else if (e1.priority === e2.priority) return 0
202
203 return 1
204 })
205 .map(e => e.name)
206 }
207
1896bca0
C
208 private buildAvailableProfiles () {
209 for (const type of [ 'vod', 'live' ]) {
210 const result = new Set()
211
212 const encoders = this.availableEncoders[type]
213
214 for (const encoderName of Object.keys(encoders)) {
215 for (const profile of Object.keys(encoders[encoderName])) {
216 result.add(profile)
217 }
218 }
219
220 this.availableProfiles[type] = Array.from(result)
221 }
222
223 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
224 }
225
226 private buildDefaultEncodersPriorities () {
227 return {
228 video: [
229 { name: 'libx264', priority: 100 }
230 ],
231
232 // Try the first one, if not available try the second one etc
233 audio: [
234 // we favor VBR, if a good AAC encoder is available
235 { name: 'libfdk_aac', priority: 200 },
236 { name: 'aac', priority: 100 }
237 ]
238 }
239 }
240
529b3752
C
241 static get Instance () {
242 return this.instance || (this.instance = new this())
5a547f69
C
243 }
244}
245
246// ---------------------------------------------------------------------------
247
248export {
529b3752 249 VideoTranscodingProfilesManager
5a547f69
C
250}
251
252// ---------------------------------------------------------------------------
c826f34a 253
67eeec8b
C
254function getTargetBitrate (options: {
255 inputBitrate: number
256 resolution: VideoResolution
257 ratio: number
258 fps: number
259}) {
260 const { inputBitrate, resolution, ratio, fps } = options
261
262 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
263 const limit = getMinLimitBitrate({ resolution, fps, ratio })
264
265 return Math.max(limit, capped)
266}
267
679c12e6 268function capBitrate (inputBitrate: number, targetBitrate: number) {
c826f34a 269 if (!inputBitrate) return targetBitrate
884d2c39 270
41085b15
C
271 // Add 30% margin to input bitrate
272 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
273
274 return Math.min(targetBitrate, inputBitrateWithMargin)
884d2c39 275}
14857212 276
7f529402 277function getCommonOutputOptions (targetBitrate: number, streamNum?: number) {
14857212
C
278 return [
279 `-preset veryfast`,
7f529402
C
280 `${buildStreamSuffix('-maxrate:v', streamNum)} ${targetBitrate}`,
281 `${buildStreamSuffix('-bufsize:v', streamNum)} ${targetBitrate * 2}`,
14857212
C
282
283 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
284 `-b_strategy 1`,
285 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
286 `-bf 16`
287 ]
288}