]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/ffmpeg-utils.ts
17f35fe8d2ebe88919a2925912cc839fe6dc9e45
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { join } from 'path'
3 import { VideoResolution, getTargetBitrate } from '../../shared/models/videos'
4 import { CONFIG, FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers'
5 import { processImage } from './image-utils'
6 import { logger } from './logger'
7 import { checkFFmpegEncoders } from '../initializers/checker-before-init'
8 import { remove } from 'fs-extra'
9
10 function computeResolutionsToTranscode (videoFileHeight: number) {
11 const resolutionsEnabled: number[] = []
12 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
13
14 // Put in the order we want to proceed jobs
15 const resolutions = [
16 VideoResolution.H_480P,
17 VideoResolution.H_360P,
18 VideoResolution.H_720P,
19 VideoResolution.H_240P,
20 VideoResolution.H_1080P
21 ]
22
23 for (const resolution of resolutions) {
24 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
25 resolutionsEnabled.push(resolution)
26 }
27 }
28
29 return resolutionsEnabled
30 }
31
32 async function getVideoFileResolution (path: string) {
33 const videoStream = await getVideoFileStream(path)
34
35 return {
36 videoFileResolution: Math.min(videoStream.height, videoStream.width),
37 isPortraitMode: videoStream.height > videoStream.width
38 }
39 }
40
41 async function getVideoFileFPS (path: string) {
42 const videoStream = await getVideoFileStream(path)
43
44 for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
45 const valuesText: string = videoStream[key]
46 if (!valuesText) continue
47
48 const [ frames, seconds ] = valuesText.split('/')
49 if (!frames || !seconds) continue
50
51 const result = parseInt(frames, 10) / parseInt(seconds, 10)
52 if (result > 0) return Math.round(result)
53 }
54
55 return 0
56 }
57
58 async function getVideoFileBitrate (path: string) {
59 return new Promise<number>((res, rej) => {
60 ffmpeg.ffprobe(path, (err, metadata) => {
61 if (err) return rej(err)
62
63 return res(metadata.format.bit_rate)
64 })
65 })
66 }
67
68 function getDurationFromVideoFile (path: string) {
69 return new Promise<number>((res, rej) => {
70 ffmpeg.ffprobe(path, (err, metadata) => {
71 if (err) return rej(err)
72
73 return res(Math.floor(metadata.format.duration))
74 })
75 })
76 }
77
78 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
79 const pendingImageName = 'pending-' + imageName
80
81 const options = {
82 filename: pendingImageName,
83 count: 1,
84 folder
85 }
86
87 const pendingImagePath = join(folder, pendingImageName)
88
89 try {
90 await new Promise<string>((res, rej) => {
91 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
92 .on('error', rej)
93 .on('end', () => res(imageName))
94 .thumbnail(options)
95 })
96
97 const destination = join(folder, imageName)
98 await processImage({ path: pendingImagePath }, destination, size)
99 } catch (err) {
100 logger.error('Cannot generate image from video %s.', fromPath, { err })
101
102 try {
103 await remove(pendingImagePath)
104 } catch (err) {
105 logger.debug('Cannot remove pending image path after generation error.', { err })
106 }
107 }
108 }
109
110 type TranscodeOptions = {
111 inputPath: string
112 outputPath: string
113 resolution?: VideoResolution
114 isPortraitMode?: boolean
115 }
116
117 function transcode (options: TranscodeOptions) {
118 return new Promise<void>(async (res, rej) => {
119 let fps = await getVideoFileFPS(options.inputPath)
120 // On small/medium resolutions, limit FPS
121 if (options.resolution !== undefined &&
122 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
123 fps > VIDEO_TRANSCODING_FPS.AVERAGE) {
124 fps = VIDEO_TRANSCODING_FPS.AVERAGE
125 }
126
127 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
128 .output(options.outputPath)
129 command = await presetH264(command, options.resolution, fps)
130
131 if (CONFIG.TRANSCODING.THREADS > 0) {
132 // if we don't set any threads ffmpeg will chose automatically
133 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
134 }
135
136 if (options.resolution !== undefined) {
137 // '?x720' or '720x?' for example
138 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
139 command = command.size(size)
140 }
141
142 if (fps) {
143 // Hard FPS limits
144 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
145 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
146
147 command = command.withFPS(fps)
148 }
149
150 command
151 .on('error', (err, stdout, stderr) => {
152 logger.error('Error in transcoding job.', { stdout, stderr })
153 return rej(err)
154 })
155 .on('end', res)
156 .run()
157 })
158 }
159
160 // ---------------------------------------------------------------------------
161
162 export {
163 getVideoFileResolution,
164 getDurationFromVideoFile,
165 generateImageFromVideoFile,
166 transcode,
167 getVideoFileFPS,
168 computeResolutionsToTranscode,
169 audio,
170 getVideoFileBitrate
171 }
172
173 // ---------------------------------------------------------------------------
174
175 function getVideoFileStream (path: string) {
176 return new Promise<any>((res, rej) => {
177 ffmpeg.ffprobe(path, (err, metadata) => {
178 if (err) return rej(err)
179
180 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
181 if (!videoStream) throw new Error('Cannot find video stream of ' + path)
182
183 return res(videoStream)
184 })
185 })
186 }
187
188 /**
189 * A slightly customised version of the 'veryfast' x264 preset
190 *
191 * The veryfast preset is right in the sweet spot of performance
192 * and quality. Superfast and ultrafast will give you better
193 * performance, but then quality is noticeably worse.
194 */
195 async function presetH264VeryFast (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
196 const localFfmpeg = await presetH264(ffmpeg, resolution, fps)
197 localFfmpeg
198 .outputOption('-preset:v veryfast')
199 .outputOption(['--aq-mode=2', '--aq-strength=1.3'])
200 /*
201 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
202 Our target situation is closer to a livestream than a stream,
203 since we want to reduce as much a possible the encoding burden,
204 altough not to the point of a livestream where there is a hard
205 constraint on the frames per second to be encoded.
206
207 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
208 Make up for most of the loss of grain and macroblocking
209 with less computing power.
210 */
211 }
212
213 /**
214 * A preset optimised for a stillimage audio video
215 */
216 async function presetStillImageWithAudio (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
217 const localFfmpeg = await presetH264VeryFast(ffmpeg, resolution, fps)
218 localFfmpeg
219 .outputOption('-tune stillimage')
220 }
221
222 /**
223 * A toolbox to play with audio
224 */
225 namespace audio {
226 export const get = (_ffmpeg, pos: number | string = 0) => {
227 // without position, ffprobe considers the last input only
228 // we make it consider the first input only
229 // if you pass a file path to pos, then ffprobe acts on that file directly
230 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
231 _ffmpeg.ffprobe(pos, (err,data) => {
232 if (err) return rej(err)
233
234 if ('streams' in data) {
235 const audioStream = data['streams'].find(stream => stream['codec_type'] === 'audio')
236 if (audioStream) {
237 return res({
238 absolutePath: data.format.filename,
239 audioStream
240 })
241 }
242 }
243 return res({ absolutePath: data.format.filename })
244 })
245 })
246 }
247
248 export namespace bitrate {
249 const baseKbitrate = 384
250
251 const toBits = (kbits: number): number => { return kbits * 8000 }
252
253 export const aac = (bitrate: number): number => {
254 switch (true) {
255 case bitrate > toBits(baseKbitrate):
256 return baseKbitrate
257 default:
258 return -1 // we interpret it as a signal to copy the audio stream as is
259 }
260 }
261
262 export const mp3 = (bitrate: number): number => {
263 /*
264 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
265 That's why, when using aac, we can go to lower kbit/sec. The equivalences
266 made here are not made to be accurate, especially with good mp3 encoders.
267 */
268 switch (true) {
269 case bitrate <= toBits(192):
270 return 128
271 case bitrate <= toBits(384):
272 return 256
273 default:
274 return baseKbitrate
275 }
276 }
277 }
278 }
279
280 /**
281 * Standard profile, with variable bitrate audio and faststart.
282 *
283 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
284 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
285 */
286 async function presetH264 (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
287 let localFfmpeg = ffmpeg
288 .format('mp4')
289 .videoCodec('libx264')
290 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
291 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
292 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
293 .outputOption('-map_metadata -1') // strip all metadata
294 .outputOption('-movflags faststart')
295 const _audio = await audio.get(localFfmpeg)
296
297 if (!_audio.audioStream) {
298 return localFfmpeg.noAudio()
299 }
300
301 // we favor VBR, if a good AAC encoder is available
302 if ((await checkFFmpegEncoders()).get('libfdk_aac')) {
303 return localFfmpeg
304 .audioCodec('libfdk_aac')
305 .audioQuality(5)
306 }
307
308 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
309 // of course this is far from perfect, but it might save some space in the end
310 const audioCodecName = _audio.audioStream['codec_name']
311 let bitrate: number
312 if (audio.bitrate[audioCodecName]) {
313 bitrate = audio.bitrate[audioCodecName](_audio.audioStream['bit_rate'])
314
315 if (bitrate === -1) return localFfmpeg.audioCodec('copy')
316 }
317
318 if (bitrate !== undefined) return localFfmpeg.audioBitrate(bitrate)
319
320 // Constrained Encoding (VBV)
321 // https://slhck.info/video/2017/03/01/rate-control.html
322 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
323 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
324 localFfmpeg.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
325
326 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
327 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
328 // https://superuser.com/a/908325
329 localFfmpeg.outputOption(`-g ${ fps * 2 }`)
330
331 return localFfmpeg
332 }