]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/video-transcoding-profiles.ts
Use a profile manager for transcoding
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding-profiles.ts
1 import { logger } from '@server/helpers/logger'
2 import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
3 import { AvailableEncoders, buildStreamSuffix, EncoderOptionsBuilder } from '../helpers/ffmpeg-utils'
4 import {
5 canDoQuickAudioTranscode,
6 ffprobePromise,
7 getAudioStream,
8 getMaxAudioBitrate,
9 getVideoFileBitrate,
10 getVideoStreamFromFile
11 } from '../helpers/ffprobe-utils'
12 import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
13
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 *
19 */
20
21 // Resources:
22 // * https://slhck.info/video/2017/03/01/rate-control.html
23 // * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
24
25 const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
26 const targetBitrate = await buildTargetBitrate({ input, resolution, fps })
27 if (!targetBitrate) return { outputOptions: [ ] }
28
29 return {
30 outputOptions: [
31 `-r ${fps}`,
32 `-maxrate ${targetBitrate}`,
33 `-bufsize ${targetBitrate * 2}`
34 ]
35 }
36 }
37
38 const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, streamNum }) => {
39 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
40
41 return {
42 outputOptions: [
43 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
44 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
45 `-maxrate ${targetBitrate}`,
46 `-bufsize ${targetBitrate * 2}`
47 ]
48 }
49 }
50
51 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
52 const probe = await ffprobePromise(input)
53
54 if (await canDoQuickAudioTranscode(input, probe)) {
55 logger.debug('Copy audio stream %s by AAC encoder.', input)
56 return { copy: true, outputOptions: [] }
57 }
58
59 const parsedAudio = await getAudioStream(input, probe)
60
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
63
64 const audioCodecName = parsedAudio.audioStream['codec_name']
65
66 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
67
68 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
69
70 if (bitrate !== undefined && bitrate !== -1) {
71 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
72 }
73
74 return { outputOptions: [ ] }
75 }
76
77 const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
78 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
79 }
80
81 // Used to get and update available encoders
82 class VideoTranscodingProfilesManager {
83 private static instance: VideoTranscodingProfilesManager
84
85 // 1 === less priority
86 private readonly encodersPriorities = {
87 video: [
88 { name: 'libx264', priority: 100 }
89 ],
90
91 // Try the first one, if not available try the second one etc
92 audio: [
93 // we favor VBR, if a good AAC encoder is available
94 { name: 'libfdk_aac', priority: 200 },
95 { name: 'aac', priority: 100 }
96 ]
97 }
98
99 private readonly availableEncoders = {
100 vod: {
101 libx264: {
102 default: defaultX264VODOptionsBuilder
103 },
104 aac: {
105 default: defaultAACOptionsBuilder
106 },
107 libfdk_aac: {
108 default: defaultLibFDKAACVODOptionsBuilder
109 }
110 },
111 live: {
112 libx264: {
113 default: defaultX264LiveOptionsBuilder
114 },
115 aac: {
116 default: defaultAACOptionsBuilder
117 }
118 }
119 }
120
121 private constructor () {
122
123 }
124
125 getAvailableEncoders (): AvailableEncoders {
126 const encodersToTry = {
127 video: this.getEncodersByPriority('video'),
128 audio: this.getEncodersByPriority('audio')
129 }
130
131 return Object.assign({}, this.availableEncoders, { encodersToTry })
132 }
133
134 getAvailableProfiles (type: 'vod' | 'live') {
135 return this.availableEncoders[type]
136 }
137
138 private getEncodersByPriority (type: 'video' | 'audio') {
139 return this.encodersPriorities[type]
140 .sort((e1, e2) => {
141 if (e1.priority > e2.priority) return -1
142 else if (e1.priority === e2.priority) return 0
143
144 return 1
145 })
146 .map(e => e.name)
147 }
148
149 static get Instance () {
150 return this.instance || (this.instance = new this())
151 }
152 }
153
154 // ---------------------------------------------------------------------------
155
156 export {
157 VideoTranscodingProfilesManager
158 }
159
160 // ---------------------------------------------------------------------------
161 async function buildTargetBitrate (options: {
162 input: string
163 resolution: VideoResolution
164 fps: number
165 }) {
166 const { input, resolution, fps } = options
167 const probe = await ffprobePromise(input)
168
169 const videoStream = await getVideoStreamFromFile(input, probe)
170 if (!videoStream) return undefined
171
172 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
173
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)
177 }