]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/transcoding/default-transcoding-profiles.ts
Add basic video editor support
[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: [
14857212
C
52 ...getCommonOutputOptions(targetBitrate),
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
5ac64497 79 if (bitrate !== -1) {
a60696ab 80 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
5a547f69
C
81 }
82
a60696ab 83 return { outputOptions: [ ] }
5a547f69
C
84}
85
86const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
a60696ab 87 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
5a547f69
C
88}
89
c729caf6
C
90// ---------------------------------------------------------------------------
91// Profile manager to get and change default profiles
92// ---------------------------------------------------------------------------
93
529b3752
C
94class VideoTranscodingProfilesManager {
95 private static instance: VideoTranscodingProfilesManager
96
97 // 1 === less priority
98 private readonly encodersPriorities = {
1896bca0
C
99 vod: this.buildDefaultEncodersPriorities(),
100 live: this.buildDefaultEncodersPriorities()
529b3752
C
101 }
102
103 private readonly availableEncoders = {
104 vod: {
105 libx264: {
106 default: defaultX264VODOptionsBuilder
107 },
108 aac: {
109 default: defaultAACOptionsBuilder
110 },
111 libfdk_aac: {
112 default: defaultLibFDKAACVODOptionsBuilder
113 }
5a547f69 114 },
529b3752
C
115 live: {
116 libx264: {
117 default: defaultX264LiveOptionsBuilder
118 },
119 aac: {
120 default: defaultAACOptionsBuilder
121 }
5a547f69 122 }
529b3752
C
123 }
124
1896bca0
C
125 private availableProfiles = {
126 vod: [] as string[],
127 live: [] as string[]
128 }
529b3752 129
1896bca0
C
130 private constructor () {
131 this.buildAvailableProfiles()
529b3752
C
132 }
133
134 getAvailableEncoders (): AvailableEncoders {
1896bca0
C
135 return {
136 available: this.availableEncoders,
137 encodersToTry: {
138 vod: {
139 video: this.getEncodersByPriority('vod', 'video'),
140 audio: this.getEncodersByPriority('vod', 'audio')
141 },
142 live: {
143 video: this.getEncodersByPriority('live', 'video'),
144 audio: this.getEncodersByPriority('live', 'audio')
145 }
146 }
5a547f69 147 }
529b3752
C
148 }
149
150 getAvailableProfiles (type: 'vod' | 'live') {
1896bca0
C
151 return this.availableProfiles[type]
152 }
153
154 addProfile (options: {
155 type: 'vod' | 'live'
156 encoder: string
157 profile: string
158 builder: EncoderOptionsBuilder
159 }) {
160 const { type, encoder, profile, builder } = options
161
162 const encoders = this.availableEncoders[type]
163
164 if (!encoders[encoder]) encoders[encoder] = {}
165 encoders[encoder][profile] = builder
166
167 this.buildAvailableProfiles()
168 }
169
170 removeProfile (options: {
171 type: 'vod' | 'live'
172 encoder: string
173 profile: string
174 }) {
175 const { type, encoder, profile } = options
176
177 delete this.availableEncoders[type][encoder][profile]
178 this.buildAvailableProfiles()
529b3752
C
179 }
180
1896bca0
C
181 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
182 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
183
184 resetSupportedEncoders()
185 }
186
187 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
188 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
189 .filter(o => o.name !== encoder && o.priority !== priority)
190
191 resetSupportedEncoders()
192 }
193
194 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
195 return this.encodersPriorities[type][streamType]
529b3752
C
196 .sort((e1, e2) => {
197 if (e1.priority > e2.priority) return -1
198 else if (e1.priority === e2.priority) return 0
199
200 return 1
201 })
202 .map(e => e.name)
203 }
204
1896bca0
C
205 private buildAvailableProfiles () {
206 for (const type of [ 'vod', 'live' ]) {
207 const result = new Set()
208
209 const encoders = this.availableEncoders[type]
210
211 for (const encoderName of Object.keys(encoders)) {
212 for (const profile of Object.keys(encoders[encoderName])) {
213 result.add(profile)
214 }
215 }
216
217 this.availableProfiles[type] = Array.from(result)
218 }
219
220 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
221 }
222
223 private buildDefaultEncodersPriorities () {
224 return {
225 video: [
226 { name: 'libx264', priority: 100 }
227 ],
228
229 // Try the first one, if not available try the second one etc
230 audio: [
231 // we favor VBR, if a good AAC encoder is available
232 { name: 'libfdk_aac', priority: 200 },
233 { name: 'aac', priority: 100 }
234 ]
235 }
236 }
237
529b3752
C
238 static get Instance () {
239 return this.instance || (this.instance = new this())
5a547f69
C
240 }
241}
242
243// ---------------------------------------------------------------------------
244
245export {
529b3752 246 VideoTranscodingProfilesManager
5a547f69
C
247}
248
249// ---------------------------------------------------------------------------
c826f34a 250
67eeec8b
C
251function getTargetBitrate (options: {
252 inputBitrate: number
253 resolution: VideoResolution
254 ratio: number
255 fps: number
256}) {
257 const { inputBitrate, resolution, ratio, fps } = options
258
259 const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
260 const limit = getMinLimitBitrate({ resolution, fps, ratio })
261
262 return Math.max(limit, capped)
263}
264
679c12e6 265function capBitrate (inputBitrate: number, targetBitrate: number) {
c826f34a 266 if (!inputBitrate) return targetBitrate
884d2c39 267
41085b15
C
268 // Add 30% margin to input bitrate
269 const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)
270
271 return Math.min(targetBitrate, inputBitrateWithMargin)
884d2c39 272}
14857212
C
273
274function getCommonOutputOptions (targetBitrate: number) {
275 return [
276 `-preset veryfast`,
277 `-maxrate ${targetBitrate}`,
278 `-bufsize ${targetBitrate * 2}`,
279
280 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
281 `-b_strategy 1`,
282 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
283 `-bf 16`
284 ]
285}