1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { dirname, join } from 'path'
3 import { getTargetBitrate, getMaxBitrate, VideoResolution } from '../../shared/models/videos'
4 import { 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 { readFile, remove, writeFile } from 'fs-extra'
9 import { CONFIG } from '../initializers/config'
11 function computeResolutionsToTranscode (videoFileHeight: number) {
12 const resolutionsEnabled: number[] = []
13 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
15 // Put in the order we want to proceed jobs
17 VideoResolution.H_NOVIDEO,
18 VideoResolution.H_480P,
19 VideoResolution.H_360P,
20 VideoResolution.H_720P,
21 VideoResolution.H_240P,
22 VideoResolution.H_1080P,
26 for (const resolution of resolutions) {
27 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
28 resolutionsEnabled.push(resolution)
32 return resolutionsEnabled
35 async function getVideoStreamSize (path: string) {
36 const videoStream = await getVideoStreamFromFile(path)
38 return videoStream === null
39 ? { width: 0, height: 0 }
40 : { width: videoStream.width, height: videoStream.height }
43 async function getVideoStreamCodec (path: string) {
44 const videoStream = await getVideoStreamFromFile(path)
46 if (!videoStream) return ''
48 const videoCodec = videoStream.codec_tag_string
50 const baseProfileMatrix = {
56 let baseProfile = baseProfileMatrix[videoStream.profile]
58 logger.warn('Cannot get video profile codec of %s.', path, { videoStream })
59 baseProfile = baseProfileMatrix['High'] // Fallback
62 const level = videoStream.level.toString(16)
64 return `${videoCodec}.${baseProfile}${level}`
67 async function getAudioStreamCodec (path: string) {
68 const { audioStream } = await audio.get(path)
70 if (!audioStream) return ''
72 const audioCodec = audioStream.codec_name
73 if (audioCodec === 'aac') return 'mp4a.40.2'
75 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
77 return 'mp4a.40.2' // Fallback
80 async function getVideoFileResolution (path: string) {
81 const size = await getVideoStreamSize(path)
84 videoFileResolution: Math.min(size.height, size.width),
85 isPortraitMode: size.height > size.width
89 async function getVideoFileFPS (path: string) {
90 const videoStream = await getVideoStreamFromFile(path)
91 if (videoStream === null) return 0
93 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
94 const valuesText: string = videoStream[ key ]
95 if (!valuesText) continue
97 const [ frames, seconds ] = valuesText.split('/')
98 if (!frames || !seconds) continue
100 const result = parseInt(frames, 10) / parseInt(seconds, 10)
101 if (result > 0) return Math.round(result)
107 async function getVideoFileBitrate (path: string) {
108 return new Promise<number>((res, rej) => {
109 ffmpeg.ffprobe(path, (err, metadata) => {
110 if (err) return rej(err)
112 return res(metadata.format.bit_rate)
117 function getDurationFromVideoFile (path: string) {
118 return new Promise<number>((res, rej) => {
119 ffmpeg.ffprobe(path, (err, metadata) => {
120 if (err) return rej(err)
122 return res(Math.floor(metadata.format.duration))
127 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
128 const pendingImageName = 'pending-' + imageName
131 filename: pendingImageName,
136 const pendingImagePath = join(folder, pendingImageName)
139 await new Promise<string>((res, rej) => {
140 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
142 .on('end', () => res(imageName))
146 const destination = join(folder, imageName)
147 await processImage(pendingImagePath, destination, size)
149 logger.error('Cannot generate image from video %s.', fromPath, { err })
152 await remove(pendingImagePath)
154 logger.debug('Cannot remove pending image path after generation error.', { err })
159 type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
161 interface BaseTranscodeOptions {
162 type: TranscodeOptionsType
165 resolution: VideoResolution
166 isPortraitMode?: boolean
169 interface HLSTranscodeOptions extends BaseTranscodeOptions {
173 videoFilename: string
177 interface QuickTranscodeOptions extends BaseTranscodeOptions {
178 type: 'quick-transcode'
181 interface VideoTranscodeOptions extends BaseTranscodeOptions {
185 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
190 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
194 type TranscodeOptions = HLSTranscodeOptions
195 | VideoTranscodeOptions
196 | MergeAudioTranscodeOptions
197 | OnlyAudioTranscodeOptions
198 | QuickTranscodeOptions
200 function transcode (options: TranscodeOptions) {
201 return new Promise<void>(async (res, rej) => {
203 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
204 .output(options.outputPath)
206 if (options.type === 'quick-transcode') {
207 command = await buildQuickTranscodeCommand(command)
208 } else if (options.type === 'hls') {
209 command = await buildHLSCommand(command, options)
210 } else if (options.type === 'merge-audio') {
211 command = await buildAudioMergeCommand(command, options)
212 } else if (options.type === 'only-audio') {
213 command = await buildOnlyAudioCommand(command, options)
215 command = await buildx264Command(command, options)
218 if (CONFIG.TRANSCODING.THREADS > 0) {
219 // if we don't set any threads ffmpeg will chose automatically
220 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
224 .on('error', (err, stdout, stderr) => {
225 logger.error('Error in transcoding job.', { stdout, stderr })
229 return fixHLSPlaylistIfNeeded(options)
231 .catch(err => rej(err))
240 async function canDoQuickTranscode (path: string): Promise<boolean> {
241 // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
242 const videoStream = await getVideoStreamFromFile(path)
243 const parsedAudio = await audio.get(path)
244 const fps = await getVideoFileFPS(path)
245 const bitRate = await getVideoFileBitrate(path)
246 const resolution = await getVideoFileResolution(path)
248 // check video params
249 if (videoStream == null) return false
250 if (videoStream[ 'codec_name' ] !== 'h264') return false
251 if (videoStream[ 'pix_fmt' ] !== 'yuv420p') return false
252 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
253 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
255 // check audio params (if audio stream exists)
256 if (parsedAudio.audioStream) {
257 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
259 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
260 if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
266 function getClosestFramerateStandard (fps: number, hd = false): number {
267 return VIDEO_TRANSCODING_FPS[hd ? 'HD_STANDARD' : 'STANDARD'].slice(0).sort((a, b) => fps % a - fps % b)[0]
270 // ---------------------------------------------------------------------------
276 getVideoFileResolution,
277 getDurationFromVideoFile,
278 generateImageFromVideoFile,
280 TranscodeOptionsType,
283 computeResolutionsToTranscode,
289 // ---------------------------------------------------------------------------
291 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
292 let fps = await getVideoFileFPS(options.inputPath)
294 // On small/medium resolutions, limit FPS
295 options.resolution !== undefined &&
296 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
297 fps > VIDEO_TRANSCODING_FPS.AVERAGE ||
298 // If the video is doesn't match hd standard
299 !VIDEO_TRANSCODING_FPS.HD_STANDARD.some(value => fps % value === 0)
301 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
302 fps = getClosestFramerateStandard(fps)
305 command = await presetH264(command, options.inputPath, options.resolution, fps)
307 if (options.resolution !== undefined) {
308 // '?x720' or '720x?' for example
309 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
310 command = command.size(size)
315 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, true)
316 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
318 command = command.withFPS(fps)
324 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
325 command = command.loop(undefined)
327 command = await presetH264VeryFast(command, options.audioPath, options.resolution)
329 command = command.input(options.audioPath)
330 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
331 .outputOption('-tune stillimage')
332 .outputOption('-shortest')
337 async function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, options: OnlyAudioTranscodeOptions) {
338 command = await presetOnlyAudio(command)
343 async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
344 command = await presetCopy(command)
346 command = command.outputOption('-map_metadata -1') // strip all metadata
347 .outputOption('-movflags faststart')
352 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
353 const videoPath = getHLSVideoPath(options)
355 if (options.copyCodecs) command = await presetCopy(command)
356 else command = await buildx264Command(command, options)
358 command = command.outputOption('-hls_time 4')
359 .outputOption('-hls_list_size 0')
360 .outputOption('-hls_playlist_type vod')
361 .outputOption('-hls_segment_filename ' + videoPath)
362 .outputOption('-hls_segment_type fmp4')
363 .outputOption('-f hls')
364 .outputOption('-hls_flags single_file')
369 function getHLSVideoPath (options: HLSTranscodeOptions) {
370 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
373 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
374 if (options.type !== 'hls') return
376 const fileContent = await readFile(options.outputPath)
378 const videoFileName = options.hlsPlaylist.videoFilename
379 const videoFilePath = getHLSVideoPath(options)
381 // Fix wrong mapping with some ffmpeg versions
382 const newContent = fileContent.toString()
383 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
385 await writeFile(options.outputPath, newContent)
388 function getVideoStreamFromFile (path: string) {
389 return new Promise<any>((res, rej) => {
390 ffmpeg.ffprobe(path, (err, metadata) => {
391 if (err) return rej(err)
393 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
394 return res(videoStream || null)
400 * A slightly customised version of the 'veryfast' x264 preset
402 * The veryfast preset is right in the sweet spot of performance
403 * and quality. Superfast and ultrafast will give you better
404 * performance, but then quality is noticeably worse.
406 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
407 let localCommand = await presetH264(command, input, resolution, fps)
409 localCommand = localCommand.outputOption('-preset:v veryfast')
412 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
413 Our target situation is closer to a livestream than a stream,
414 since we want to reduce as much a possible the encoding burden,
415 although not to the point of a livestream where there is a hard
416 constraint on the frames per second to be encoded.
423 * A toolbox to play with audio
426 export const get = (videoPath: string) => {
427 // without position, ffprobe considers the last input only
428 // we make it consider the first input only
429 // if you pass a file path to pos, then ffprobe acts on that file directly
430 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
432 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
433 if (err) return rej(err)
435 if ('streams' in data) {
436 const audioStream = data.streams.find(stream => stream[ 'codec_type' ] === 'audio')
439 absolutePath: data.format.filename,
445 return res({ absolutePath: data.format.filename })
448 return ffmpeg.ffprobe(videoPath, parseFfprobe)
452 export namespace bitrate {
453 const baseKbitrate = 384
455 const toBits = (kbits: number) => kbits * 8000
457 export const aac = (bitrate: number): number => {
459 case bitrate > toBits(baseKbitrate):
463 return -1 // we interpret it as a signal to copy the audio stream as is
467 export const mp3 = (bitrate: number): number => {
469 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
470 That's why, when using aac, we can go to lower kbit/sec. The equivalences
471 made here are not made to be accurate, especially with good mp3 encoders.
474 case bitrate <= toBits(192):
477 case bitrate <= toBits(384):
488 * Standard profile, with variable bitrate audio and faststart.
490 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
491 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
493 async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
494 let localCommand = command
496 .videoCodec('libx264')
497 .outputOption('-level 3.1') // 3.1 is the minimal resource allocation for our highest supported resolution
498 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
499 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
500 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
501 .outputOption('-map_metadata -1') // strip all metadata
502 .outputOption('-movflags faststart')
504 const parsedAudio = await audio.get(input)
506 if (!parsedAudio.audioStream) {
507 localCommand = localCommand.noAudio()
508 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
509 localCommand = localCommand
510 .audioCodec('libfdk_aac')
513 // we try to reduce the ceiling bitrate by making rough matches of bitrates
514 // of course this is far from perfect, but it might save some space in the end
515 localCommand = localCommand.audioCodec('aac')
517 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
519 if (audio.bitrate[ audioCodecName ]) {
520 const bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
521 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
526 // Constrained Encoding (VBV)
527 // https://slhck.info/video/2017/03/01/rate-control.html
528 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
529 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
530 localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
532 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
533 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
534 // https://superuser.com/a/908325
535 localCommand = localCommand.outputOption(`-g ${fps * 2}`)
541 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {
548 async function presetOnlyAudio (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {