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