]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg-utils.ts
Add list of instance follows in about page
[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
536598cf
C
120type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio'
121
122interface BaseTranscodeOptions {
123 type: TranscodeOptionsType
14d3270f
C
124 inputPath: string
125 outputPath: string
09209296 126 resolution: VideoResolution
056aa7f2 127 isPortraitMode?: boolean
536598cf 128}
09209296 129
536598cf
C
130interface HLSTranscodeOptions extends BaseTranscodeOptions {
131 type: 'hls'
132 hlsPlaylist: {
4c280004
C
133 videoFilename: string
134 }
14d3270f
C
135}
136
536598cf
C
137interface QuickTranscodeOptions extends BaseTranscodeOptions {
138 type: 'quick-transcode'
139}
140
141interface VideoTranscodeOptions extends BaseTranscodeOptions {
142 type: 'video'
143}
144
145interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
146 type: 'merge-audio'
147 audioPath: string
148}
149
150type TranscodeOptions = HLSTranscodeOptions | VideoTranscodeOptions | MergeAudioTranscodeOptions | QuickTranscodeOptions
151
14d3270f 152function transcode (options: TranscodeOptions) {
73c69591 153 return new Promise<void>(async (res, rej) => {
cdf4cb9e 154 try {
cdf4cb9e
C
155 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
156 .output(options.outputPath)
14aed608 157
536598cf
C
158 if (options.type === 'quick-transcode') {
159 command = await buildQuickTranscodeCommand(command)
160 } else if (options.type === 'hls') {
14aed608 161 command = await buildHLSCommand(command, options)
536598cf
C
162 } else if (options.type === 'merge-audio') {
163 command = await buildAudioMergeCommand(command, options)
14aed608
C
164 } else {
165 command = await buildx264Command(command, options)
166 }
7160878c 167
cdf4cb9e
C
168 if (CONFIG.TRANSCODING.THREADS > 0) {
169 // if we don't set any threads ffmpeg will chose automatically
170 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
171 }
14d3270f 172
cdf4cb9e
C
173 command
174 .on('error', (err, stdout, stderr) => {
175 logger.error('Error in transcoding job.', { stdout, stderr })
176 return rej(err)
177 })
7f8f8bdb 178 .on('end', () => {
536598cf 179 return fixHLSPlaylistIfNeeded(options)
7f8f8bdb
C
180 .then(() => res())
181 .catch(err => rej(err))
182 })
cdf4cb9e
C
183 .run()
184 } catch (err) {
185 return rej(err)
186 }
14d3270f
C
187 })
188}
189
7ed2c1a4 190async function canDoQuickTranscode (path: string): Promise<boolean> {
5ba49f26
FA
191 // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
192 const videoStream = await getVideoStreamFromFile(path)
193 const parsedAudio = await audio.get(path)
194 const fps = await getVideoFileFPS(path)
195 const bitRate = await getVideoFileBitrate(path)
196 const resolution = await getVideoFileResolution(path)
197
198 // check video params
1600235a
C
199 if (videoStream[ 'codec_name' ] !== 'h264') return false
200 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
201 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
5ba49f26
FA
202
203 // check audio params (if audio stream exists)
204 if (parsedAudio.audioStream) {
1600235a
C
205 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
206
5ba49f26 207 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
1600235a 208 if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
5ba49f26 209 }
7ed2c1a4 210
5ba49f26
FA
211 return true
212}
213
14d3270f
C
214// ---------------------------------------------------------------------------
215
216export {
09209296 217 getVideoFileSize,
056aa7f2 218 getVideoFileResolution,
14d3270f
C
219 getDurationFromVideoFile,
220 generateImageFromVideoFile,
536598cf
C
221 TranscodeOptions,
222 TranscodeOptionsType,
73c69591 223 transcode,
7160878c 224 getVideoFileFPS,
06215f15 225 computeResolutionsToTranscode,
edb4ffc7 226 audio,
5ba49f26
FA
227 getVideoFileBitrate,
228 canDoQuickTranscode
73c69591
C
229}
230
231// ---------------------------------------------------------------------------
232
536598cf 233async function buildx264Command (command: ffmpeg.FfmpegCommand, options: VideoTranscodeOptions) {
14aed608
C
234 let fps = await getVideoFileFPS(options.inputPath)
235 // On small/medium resolutions, limit FPS
236 if (
237 options.resolution !== undefined &&
238 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
239 fps > VIDEO_TRANSCODING_FPS.AVERAGE
240 ) {
241 fps = VIDEO_TRANSCODING_FPS.AVERAGE
242 }
243
536598cf 244 command = await presetH264(command, options.inputPath, options.resolution, fps)
14aed608
C
245
246 if (options.resolution !== undefined) {
247 // '?x720' or '720x?' for example
248 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
249 command = command.size(size)
250 }
251
252 if (fps) {
253 // Hard FPS limits
254 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
255 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
256
257 command = command.withFPS(fps)
258 }
259
260 return command
261}
262
536598cf
C
263async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
264 command = command.loop(undefined)
265
266 command = await presetH264VeryFast(command, options.audioPath, options.resolution)
267
268 command = command.input(options.audioPath)
269 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
270 .outputOption('-tune stillimage')
271 .outputOption('-shortest')
272
273 return command
274}
275
276async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
277 command = await presetCopy(command)
278
279 command = command.outputOption('-map_metadata -1') // strip all metadata
280 .outputOption('-movflags faststart')
281
282 return command
283}
284
285async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
14aed608
C
286 const videoPath = getHLSVideoPath(options)
287
288 command = await presetCopy(command)
289
290 command = command.outputOption('-hls_time 4')
291 .outputOption('-hls_list_size 0')
292 .outputOption('-hls_playlist_type vod')
293 .outputOption('-hls_segment_filename ' + videoPath)
294 .outputOption('-hls_segment_type fmp4')
295 .outputOption('-f hls')
296 .outputOption('-hls_flags single_file')
297
298 return command
299}
300
536598cf 301function getHLSVideoPath (options: HLSTranscodeOptions) {
7f8f8bdb
C
302 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
303}
304
536598cf
C
305async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
306 if (options.type !== 'hls') return
7f8f8bdb 307
7f8f8bdb
C
308 const fileContent = await readFile(options.outputPath)
309
310 const videoFileName = options.hlsPlaylist.videoFilename
311 const videoFilePath = getHLSVideoPath(options)
312
536598cf 313 // Fix wrong mapping with some ffmpeg versions
7f8f8bdb
C
314 const newContent = fileContent.toString()
315 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
316
317 await writeFile(options.outputPath, newContent)
318}
319
5ba49f26 320function getVideoStreamFromFile (path: string) {
73c69591
C
321 return new Promise<any>((res, rej) => {
322 ffmpeg.ffprobe(path, (err, metadata) => {
323 if (err) return rej(err)
324
325 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
9ecac97b 326 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
73c69591
C
327
328 return res(videoStream)
329 })
330 })
14d3270f 331}
4176e227
RK
332
333/**
334 * A slightly customised version of the 'veryfast' x264 preset
335 *
336 * The veryfast preset is right in the sweet spot of performance
337 * and quality. Superfast and ultrafast will give you better
338 * performance, but then quality is noticeably worse.
339 */
536598cf
C
340async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
341 let localCommand = await presetH264(command, input, resolution, fps)
342
cdf4cb9e 343 localCommand = localCommand.outputOption('-preset:v veryfast')
536598cf 344
4176e227
RK
345 /*
346 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
347 Our target situation is closer to a livestream than a stream,
348 since we want to reduce as much a possible the encoding burden,
536598cf 349 although not to the point of a livestream where there is a hard
4176e227 350 constraint on the frames per second to be encoded.
4176e227 351 */
cdf4cb9e
C
352
353 return localCommand
4176e227
RK
354}
355
4176e227
RK
356/**
357 * A toolbox to play with audio
358 */
359namespace audio {
536598cf 360 export const get = (option: string) => {
4176e227
RK
361 // without position, ffprobe considers the last input only
362 // we make it consider the first input only
4a5ccac5 363 // if you pass a file path to pos, then ffprobe acts on that file directly
7160878c 364 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
cdf4cb9e
C
365
366 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
7160878c
RK
367 if (err) return rej(err)
368
369 if ('streams' in data) {
cdf4cb9e 370 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
7160878c
RK
371 if (audioStream) {
372 return res({
373 absolutePath: data.format.filename,
374 audioStream
375 })
4a5ccac5 376 }
7160878c 377 }
cdf4cb9e 378
7160878c 379 return res({ absolutePath: data.format.filename })
cdf4cb9e
C
380 }
381
536598cf 382 return ffmpeg.ffprobe(option, parseFfprobe)
4a5ccac5 383 })
4176e227
RK
384 }
385
386 export namespace bitrate {
eed24d26 387 const baseKbitrate = 384
4176e227
RK
388
389 const toBits = (kbits: number): number => { return kbits * 8000 }
390
391 export const aac = (bitrate: number): number => {
392 switch (true) {
7160878c 393 case bitrate > toBits(baseKbitrate):
4176e227
RK
394 return baseKbitrate
395 default:
396 return -1 // we interpret it as a signal to copy the audio stream as is
397 }
398 }
399
400 export const mp3 = (bitrate: number): number => {
7160878c
RK
401 /*
402 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
403 That's why, when using aac, we can go to lower kbit/sec. The equivalences
404 made here are not made to be accurate, especially with good mp3 encoders.
405 */
4176e227
RK
406 switch (true) {
407 case bitrate <= toBits(192):
408 return 128
409 case bitrate <= toBits(384):
410 return 256
411 default:
412 return baseKbitrate
413 }
414 }
415 }
416}
417
418/**
419 * Standard profile, with variable bitrate audio and faststart.
420 *
421 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
422 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
423 */
536598cf 424async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
cdf4cb9e 425 let localCommand = command
4176e227
RK
426 .format('mp4')
427 .videoCodec('libx264')
428 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
429 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
430 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
408f50eb 431 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
4a5ccac5 432 .outputOption('-map_metadata -1') // strip all metadata
4176e227 433 .outputOption('-movflags faststart')
4176e227 434
536598cf 435 const parsedAudio = await audio.get(input)
4176e227 436
cdf4cb9e
C
437 if (!parsedAudio.audioStream) {
438 localCommand = localCommand.noAudio()
439 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
440 localCommand = localCommand
4176e227
RK
441 .audioCodec('libfdk_aac')
442 .audioQuality(5)
cdf4cb9e 443 } else {
536598cf 444 // we try to reduce the ceiling bitrate by making rough matches of bitrates
cdf4cb9e 445 // of course this is far from perfect, but it might save some space in the end
536598cf
C
446 localCommand = localCommand.audioCodec('aac')
447
cdf4cb9e 448 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
cdf4cb9e 449
536598cf
C
450 if (audio.bitrate[ audioCodecName ]) {
451 const bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
64e3e270 452 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
cdf4cb9e 453 }
4176e227
RK
454 }
455
536598cf
C
456 if (fps) {
457 // Constrained Encoding (VBV)
458 // https://slhck.info/video/2017/03/01/rate-control.html
459 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
460 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
461 localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
462
463 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
464 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
465 // https://superuser.com/a/908325
466 localCommand = localCommand.outputOption(`-g ${fps * 2}`)
467 }
bcf21a37 468
cdf4cb9e 469 return localCommand
4176e227 470}
14aed608
C
471
472async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {
473 return command
474 .format('mp4')
475 .videoCodec('copy')
476 .audioCodec('copy')
477}