]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/ffmpeg-utils.ts
c477e2e89fb763a772d7b81537607fcd1d76bcc0
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { dirname, join } from 'path'
3 import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
4 import { CONFIG, FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers/constants'
5 import { processImage } from './image-utils'
6 import { logger } from './logger'
7 import { checkFFmpegEncoders } from '../initializers/checker-before-init'
8 import { remove, readFile, writeFile } 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 getVideoFileSize (path: string) {
33 const videoStream = await getVideoFileStream(path)
34
35 return {
36 width: videoStream.width,
37 height: videoStream.height
38 }
39 }
40
41 async function getVideoFileResolution (path: string) {
42 const size = await getVideoFileSize(path)
43
44 return {
45 videoFileResolution: Math.min(size.height, size.width),
46 isPortraitMode: size.height > size.width
47 }
48 }
49
50 async function getVideoFileFPS (path: string) {
51 const videoStream = await getVideoFileStream(path)
52
53 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
54 const valuesText: string = videoStream[key]
55 if (!valuesText) continue
56
57 const [ frames, seconds ] = valuesText.split('/')
58 if (!frames || !seconds) continue
59
60 const result = parseInt(frames, 10) / parseInt(seconds, 10)
61 if (result > 0) return Math.round(result)
62 }
63
64 return 0
65 }
66
67 async function getVideoFileBitrate (path: string) {
68 return new Promise<number>((res, rej) => {
69 ffmpeg.ffprobe(path, (err, metadata) => {
70 if (err) return rej(err)
71
72 return res(metadata.format.bit_rate)
73 })
74 })
75 }
76
77 function getDurationFromVideoFile (path: string) {
78 return new Promise<number>((res, rej) => {
79 ffmpeg.ffprobe(path, (err, metadata) => {
80 if (err) return rej(err)
81
82 return res(Math.floor(metadata.format.duration))
83 })
84 })
85 }
86
87 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
88 const pendingImageName = 'pending-' + imageName
89
90 const options = {
91 filename: pendingImageName,
92 count: 1,
93 folder
94 }
95
96 const pendingImagePath = join(folder, pendingImageName)
97
98 try {
99 await new Promise<string>((res, rej) => {
100 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
101 .on('error', rej)
102 .on('end', () => res(imageName))
103 .thumbnail(options)
104 })
105
106 const destination = join(folder, imageName)
107 await processImage({ path: pendingImagePath }, destination, size)
108 } catch (err) {
109 logger.error('Cannot generate image from video %s.', fromPath, { err })
110
111 try {
112 await remove(pendingImagePath)
113 } catch (err) {
114 logger.debug('Cannot remove pending image path after generation error.', { err })
115 }
116 }
117 }
118
119 type TranscodeOptions = {
120 inputPath: string
121 outputPath: string
122 resolution: VideoResolution
123 isPortraitMode?: boolean
124
125 hlsPlaylist?: {
126 videoFilename: string
127 }
128 }
129
130 function transcode (options: TranscodeOptions) {
131 return new Promise<void>(async (res, rej) => {
132 try {
133 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
134 .output(options.outputPath)
135
136 if (options.hlsPlaylist) {
137 command = await buildHLSCommand(command, options)
138 } else {
139 command = await buildx264Command(command, options)
140 }
141
142 if (CONFIG.TRANSCODING.THREADS > 0) {
143 // if we don't set any threads ffmpeg will chose automatically
144 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
145 }
146
147 command
148 .on('error', (err, stdout, stderr) => {
149 logger.error('Error in transcoding job.', { stdout, stderr })
150 return rej(err)
151 })
152 .on('end', () => {
153 return onTranscodingSuccess(options)
154 .then(() => res())
155 .catch(err => rej(err))
156 })
157 .run()
158 } catch (err) {
159 return rej(err)
160 }
161 })
162 }
163
164 // ---------------------------------------------------------------------------
165
166 export {
167 getVideoFileSize,
168 getVideoFileResolution,
169 getDurationFromVideoFile,
170 generateImageFromVideoFile,
171 transcode,
172 getVideoFileFPS,
173 computeResolutionsToTranscode,
174 audio,
175 getVideoFileBitrate
176 }
177
178 // ---------------------------------------------------------------------------
179
180 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
181 let fps = await getVideoFileFPS(options.inputPath)
182 // On small/medium resolutions, limit FPS
183 if (
184 options.resolution !== undefined &&
185 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
186 fps > VIDEO_TRANSCODING_FPS.AVERAGE
187 ) {
188 fps = VIDEO_TRANSCODING_FPS.AVERAGE
189 }
190
191 command = await presetH264(command, options.resolution, fps)
192
193 if (options.resolution !== undefined) {
194 // '?x720' or '720x?' for example
195 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
196 command = command.size(size)
197 }
198
199 if (fps) {
200 // Hard FPS limits
201 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
202 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
203
204 command = command.withFPS(fps)
205 }
206
207 return command
208 }
209
210 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
211 const videoPath = getHLSVideoPath(options)
212
213 command = await presetCopy(command)
214
215 command = command.outputOption('-hls_time 4')
216 .outputOption('-hls_list_size 0')
217 .outputOption('-hls_playlist_type vod')
218 .outputOption('-hls_segment_filename ' + videoPath)
219 .outputOption('-hls_segment_type fmp4')
220 .outputOption('-f hls')
221 .outputOption('-hls_flags single_file')
222
223 return command
224 }
225
226 function getHLSVideoPath (options: TranscodeOptions) {
227 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
228 }
229
230 async function onTranscodingSuccess (options: TranscodeOptions) {
231 if (!options.hlsPlaylist) return
232
233 // Fix wrong mapping with some ffmpeg versions
234 const fileContent = await readFile(options.outputPath)
235
236 const videoFileName = options.hlsPlaylist.videoFilename
237 const videoFilePath = getHLSVideoPath(options)
238
239 const newContent = fileContent.toString()
240 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
241
242 await writeFile(options.outputPath, newContent)
243 }
244
245 function getVideoFileStream (path: string) {
246 return new Promise<any>((res, rej) => {
247 ffmpeg.ffprobe(path, (err, metadata) => {
248 if (err) return rej(err)
249
250 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
251 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
252
253 return res(videoStream)
254 })
255 })
256 }
257
258 /**
259 * A slightly customised version of the 'veryfast' x264 preset
260 *
261 * The veryfast preset is right in the sweet spot of performance
262 * and quality. Superfast and ultrafast will give you better
263 * performance, but then quality is noticeably worse.
264 */
265 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
266 let localCommand = await presetH264(command, resolution, fps)
267 localCommand = localCommand.outputOption('-preset:v veryfast')
268 .outputOption([ '--aq-mode=2', '--aq-strength=1.3' ])
269 /*
270 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
271 Our target situation is closer to a livestream than a stream,
272 since we want to reduce as much a possible the encoding burden,
273 altough not to the point of a livestream where there is a hard
274 constraint on the frames per second to be encoded.
275
276 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
277 Make up for most of the loss of grain and macroblocking
278 with less computing power.
279 */
280
281 return localCommand
282 }
283
284 /**
285 * A preset optimised for a stillimage audio video
286 */
287 async function presetStillImageWithAudio (
288 command: ffmpeg.FfmpegCommand,
289 resolution: VideoResolution,
290 fps: number
291 ): Promise<ffmpeg.FfmpegCommand> {
292 let localCommand = await presetH264VeryFast(command, resolution, fps)
293 localCommand = localCommand.outputOption('-tune stillimage')
294
295 return localCommand
296 }
297
298 /**
299 * A toolbox to play with audio
300 */
301 namespace audio {
302 export const get = (option: ffmpeg.FfmpegCommand | string) => {
303 // without position, ffprobe considers the last input only
304 // we make it consider the first input only
305 // if you pass a file path to pos, then ffprobe acts on that file directly
306 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
307
308 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
309 if (err) return rej(err)
310
311 if ('streams' in data) {
312 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
313 if (audioStream) {
314 return res({
315 absolutePath: data.format.filename,
316 audioStream
317 })
318 }
319 }
320
321 return res({ absolutePath: data.format.filename })
322 }
323
324 if (typeof option === 'string') {
325 return ffmpeg.ffprobe(option, parseFfprobe)
326 }
327
328 return option.ffprobe(parseFfprobe)
329 })
330 }
331
332 export namespace bitrate {
333 const baseKbitrate = 384
334
335 const toBits = (kbits: number): number => { return kbits * 8000 }
336
337 export const aac = (bitrate: number): number => {
338 switch (true) {
339 case bitrate > toBits(baseKbitrate):
340 return baseKbitrate
341 default:
342 return -1 // we interpret it as a signal to copy the audio stream as is
343 }
344 }
345
346 export const mp3 = (bitrate: number): number => {
347 /*
348 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
349 That's why, when using aac, we can go to lower kbit/sec. The equivalences
350 made here are not made to be accurate, especially with good mp3 encoders.
351 */
352 switch (true) {
353 case bitrate <= toBits(192):
354 return 128
355 case bitrate <= toBits(384):
356 return 256
357 default:
358 return baseKbitrate
359 }
360 }
361 }
362 }
363
364 /**
365 * Standard profile, with variable bitrate audio and faststart.
366 *
367 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
368 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
369 */
370 async function presetH264 (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
371 let localCommand = command
372 .format('mp4')
373 .videoCodec('libx264')
374 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
375 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
376 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
377 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
378 .outputOption('-map_metadata -1') // strip all metadata
379 .outputOption('-movflags faststart')
380
381 const parsedAudio = await audio.get(localCommand)
382
383 if (!parsedAudio.audioStream) {
384 localCommand = localCommand.noAudio()
385 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
386 localCommand = localCommand
387 .audioCodec('libfdk_aac')
388 .audioQuality(5)
389 } else {
390 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
391 // of course this is far from perfect, but it might save some space in the end
392 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
393 let bitrate: number
394 if (audio.bitrate[ audioCodecName ]) {
395 localCommand = localCommand.audioCodec('aac')
396
397 bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
398 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
399 }
400 }
401
402 // Constrained Encoding (VBV)
403 // https://slhck.info/video/2017/03/01/rate-control.html
404 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
405 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
406 localCommand = localCommand.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
407
408 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
409 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
410 // https://superuser.com/a/908325
411 localCommand = localCommand.outputOption(`-g ${ fps * 2 }`)
412
413 return localCommand
414 }
415
416 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {
417 return command
418 .format('mp4')
419 .videoCodec('copy')
420 .audioCodec('copy')
421 }