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