import * as ffmpeg from 'fluent-ffmpeg'
import { readFile, remove, writeFile } from 'fs-extra'
import { dirname, join } from 'path'
-import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
+import { FFMPEG_NICE, VIDEO_LIVE, VIDEO_TRANSCODING_ENCODERS } from '@server/initializers/constants'
+import { VideoResolution } from '../../shared/models/videos'
import { checkFFmpegEncoders } from '../initializers/checker-before-init'
import { CONFIG } from '../initializers/config'
-import { FFMPEG_NICE, VIDEO_LIVE, VIDEO_TRANSCODING_FPS } from '../initializers/constants'
-import { getAudioStream, getClosestFramerateStandard, getMaxAudioBitrate, getVideoFileFPS } from './ffprobe-utils'
+import { computeFPS, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
import { processImage } from './image-utils'
import { logger } from './logger'
+/**
+ *
+ * Functions that run transcoding/muxing ffmpeg processes
+ * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
+ *
+ */
+
+// ---------------------------------------------------------------------------
+// Encoder options
+// ---------------------------------------------------------------------------
+
+// Options builders
+
+export type EncoderOptionsBuilder = (params: {
+ input: string
+ resolution: VideoResolution
+ fps?: number
+ streamNum?: number
+}) => Promise<EncoderOptions> | EncoderOptions
+
+// Options types
+
+export interface EncoderOptions {
+ copy?: boolean
+ outputOptions: string[]
+}
+
+// All our encoders
+
+export interface EncoderProfile <T> {
+ [ profile: string ]: T
+
+ default: T
+}
+
+export type AvailableEncoders = {
+ [ id in 'live' | 'vod' ]: {
+ [ encoder in 'libx264' | 'aac' | 'libfdk_aac' ]?: EncoderProfile<EncoderOptionsBuilder>
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Image manipulation
+// ---------------------------------------------------------------------------
+
+function convertWebPToJPG (path: string, destination: string): Promise<void> {
+ const command = ffmpeg(path)
+ .output(destination)
+
+ return runCommand(command)
+}
+
+function processGIF (
+ path: string,
+ destination: string,
+ newSize: { width: number, height: number }
+): Promise<void> {
+ const command = ffmpeg(path)
+ .fps(20)
+ .size(`${newSize.width}x${newSize.height}`)
+ .output(destination)
+
+ return runCommand(command)
+}
+
async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
const pendingImageName = 'pending-' + imageName
interface BaseTranscodeOptions {
type: TranscodeOptionsType
+
inputPath: string
outputPath: string
+
+ availableEncoders: AvailableEncoders
+ profile: string
+
resolution: VideoResolution
+
isPortraitMode?: boolean
}
'hls': buildHLSVODCommand,
'merge-audio': buildAudioMergeCommand,
'only-audio': buildOnlyAudioCommand,
- 'video': buildx264Command
+ 'video': buildx264VODCommand
}
async function transcode (options: TranscodeOptions) {
await fixHLSPlaylistIfNeeded(options)
}
-function convertWebPToJPG (path: string, destination: string): Promise<void> {
- return new Promise<void>(async (res, rej) => {
- try {
- const command = ffmpeg(path).output(destination)
-
- command.on('error', (err, stdout, stderr) => {
- logger.error('Error in ffmpeg webp convert process.', { stdout, stderr })
- return rej(err)
- })
- .on('end', () => res())
- .run()
- } catch (err) {
- return rej(err)
- }
- })
-}
-
-function processGIF (
- path: string,
- destination: string,
- newSize: { width: number, height: number },
- keepOriginal = false
-): Promise<void> {
- return new Promise<void>(async (res, rej) => {
- if (path === destination) {
- throw new Error('FFmpeg needs an input path different that the output path.')
- }
+// ---------------------------------------------------------------------------
+// Live muxing/transcoding functions
+// ---------------------------------------------------------------------------
- logger.debug('Processing gif %s to %s.', path, destination)
+async function getLiveTranscodingCommand (options: {
+ rtmpUrl: string
+ outPath: string
+ resolutions: number[]
+ fps: number
+ deleteSegments: boolean
- try {
- const command = ffmpeg(path)
- .fps(20)
- .size(`${newSize.width}x${newSize.height}`)
- .output(destination)
-
- command.on('error', (err, stdout, stderr) => {
- logger.error('Error in ffmpeg gif resizing process.', { stdout, stderr })
- return rej(err)
- })
- .on('end', async () => {
- if (keepOriginal !== true) await remove(path)
- res()
- })
- .run()
- } catch (err) {
- return rej(err)
- }
- })
-}
+ availableEncoders: AvailableEncoders
+ profile: string
+}) {
+ const { rtmpUrl, outPath, resolutions, fps, deleteSegments, availableEncoders, profile } = options
+ const input = rtmpUrl
-function runLiveTranscoding (rtmpUrl: string, outPath: string, resolutions: number[], fps, deleteSegments: boolean) {
- const command = getFFmpeg(rtmpUrl)
+ const command = getFFmpeg(input)
command.inputOption('-fflags nobuffer')
const varStreamMap: string[] = []
}))
])
- command.outputOption('-b_strategy 1')
- command.outputOption('-bf 16')
command.outputOption('-preset superfast')
- command.outputOption('-level 3.1')
- command.outputOption('-map_metadata -1')
- command.outputOption('-pix_fmt yuv420p')
- command.outputOption('-max_muxing_queue_size 1024')
- command.outputOption('-g ' + (fps * 2))
+
+ addDefaultEncoderGlobalParams({ command })
for (let i = 0; i < resolutions.length; i++) {
const resolution = resolutions[i]
+ const resolutionFPS = computeFPS(fps, resolution)
+
+ const baseEncoderBuilderParams = {
+ input,
+ availableEncoders,
+ profile,
+ fps: resolutionFPS,
+ resolution,
+ streamNum: i,
+ videoType: 'live' as 'live'
+ }
+
+ {
+ const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' }))
+ if (!builderResult) {
+ throw new Error('No available live video encoder found')
+ }
+
+ command.outputOption(`-map [vout${resolution}]`)
+
+ addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
- command.outputOption(`-map [vout${resolution}]`)
- command.outputOption(`-c:v:${i} libx264`)
- command.outputOption(`-b:v:${i} ${getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)}`)
+ logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
- command.outputOption(`-map a:0`)
- command.outputOption(`-c:a:${i} aac`)
+ command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
+ command.addOutputOptions(builderResult.result.outputOptions)
+ }
+
+ {
+ const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' }))
+ if (!builderResult) {
+ throw new Error('No available live audio encoder found')
+ }
+
+ command.outputOption('-map a:0')
+
+ addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
+
+ logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult)
+
+ command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
+ command.addOutputOptions(builderResult.result.outputOptions)
+ }
varStreamMap.push(`v:${i},a:${i}`)
}
command.outputOption('-var_stream_map', varStreamMap.join(' '))
- command.run()
-
return command
}
-function runLiveMuxing (rtmpUrl: string, outPath: string, deleteSegments: boolean) {
+function getLiveMuxingCommand (rtmpUrl: string, outPath: string, deleteSegments: boolean) {
const command = getFFmpeg(rtmpUrl)
command.inputOption('-fflags nobuffer')
addDefaultLiveHLSParams(command, outPath, deleteSegments)
- command.run()
-
return command
}
return runCommand(command, cleaner)
}
-async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
- return new Promise<string>((res, rej) => {
- command.on('error', (err, stdout, stderr) => {
- if (onEnd) onEnd()
-
- logger.error('Error in transcoding job.', { stdout, stderr })
- rej(err)
- })
-
- command.on('end', () => {
- if (onEnd) onEnd()
-
- res()
- })
+function buildStreamSuffix (base: string, streamNum?: number) {
+ if (streamNum !== undefined) {
+ return `${base}:${streamNum}`
+ }
- command.run()
- })
+ return base
}
// ---------------------------------------------------------------------------
export {
- runLiveMuxing,
+ getLiveTranscodingCommand,
+ getLiveMuxingCommand,
+ buildStreamSuffix,
convertWebPToJPG,
processGIF,
- runLiveTranscoding,
generateImageFromVideoFile,
TranscodeOptions,
TranscodeOptionsType,
// ---------------------------------------------------------------------------
-function addDefaultX264Params (command: ffmpeg.FfmpegCommand) {
- command.outputOption('-level 3.1') // 3.1 is the minimal resource allocation for our highest supported resolution
- .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
- .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
- .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
- .outputOption('-map_metadata -1') // strip all metadata
+// ---------------------------------------------------------------------------
+// Default options
+// ---------------------------------------------------------------------------
+
+function addDefaultEncoderGlobalParams (options: {
+ command: ffmpeg.FfmpegCommand
+}) {
+ const { command } = options
+
+ // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
+ command.outputOption('-max_muxing_queue_size 1024')
+ // strip all metadata
+ .outputOption('-map_metadata -1')
+ // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
+ .outputOption('-b_strategy 1')
+ // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
+ .outputOption('-bf 16')
+ // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
+ .outputOption('-pix_fmt yuv420p')
+}
+
+function addDefaultEncoderParams (options: {
+ command: ffmpeg.FfmpegCommand
+ encoder: 'libx264' | string
+ streamNum?: number
+ fps?: number
+}) {
+ const { command, encoder, fps, streamNum } = options
+
+ if (encoder === 'libx264') {
+ // 3.1 is the minimal resource allocation for our highest supported resolution
+ command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
+
+ if (fps) {
+ // Keyframe interval of 2 seconds for faster seeking and resolution switching.
+ // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
+ // https://superuser.com/a/908325
+ command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
+ }
+ }
}
function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, deleteSegments: boolean) {
command.output(join(outPath, '%v.m3u8'))
}
-async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
+// ---------------------------------------------------------------------------
+// Transcode VOD command builders
+// ---------------------------------------------------------------------------
+
+async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
let fps = await getVideoFileFPS(options.inputPath)
- if (
- // On small/medium resolutions, limit FPS
- options.resolution !== undefined &&
- options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
- fps > VIDEO_TRANSCODING_FPS.AVERAGE
- ) {
- // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
- fps = getClosestFramerateStandard(fps, 'STANDARD')
- }
+ fps = computeFPS(fps, options.resolution)
- command = await presetH264(command, options.inputPath, options.resolution, fps)
+ command = await presetVideo(command, options.inputPath, options, fps)
if (options.resolution !== undefined) {
// '?x720' or '720x?' for example
- const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
- command = command.size(size)
- }
-
- if (fps) {
- // Hard FPS limits
- if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
- else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
+ const size = options.isPortraitMode === true
+ ? `${options.resolution}x?`
+ : `?x${options.resolution}`
- command = command.withFPS(fps)
+ command = command.size(size)
}
return command
async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
command = command.loop(undefined)
- command = await presetH264VeryFast(command, options.audioPath, options.resolution)
+ command = await presetVideo(command, options.audioPath, options)
+
+ command.outputOption('-preset:v veryfast')
command = command.input(options.audioPath)
.videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
if (options.copyCodecs) command = presetCopy(command)
else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
- else command = await buildx264Command(command, options)
+ else command = await buildx264VODCommand(command, options)
command = command.outputOption('-hls_time 4')
.outputOption('-hls_list_size 0')
return command
}
-function getHLSVideoPath (options: HLSTranscodeOptions) {
- return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
-}
-
async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
if (options.type !== 'hls') return
await writeFile(options.outputPath, newContent)
}
-/**
- * A slightly customised version of the 'veryfast' x264 preset
- *
- * The veryfast preset is right in the sweet spot of performance
- * and quality. Superfast and ultrafast will give you better
- * performance, but then quality is noticeably worse.
- */
-async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
- let localCommand = await presetH264(command, input, resolution, fps)
+function getHLSVideoPath (options: HLSTranscodeOptions) {
+ return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
+}
+
+// ---------------------------------------------------------------------------
+// Transcoding presets
+// ---------------------------------------------------------------------------
- localCommand = localCommand.outputOption('-preset:v veryfast')
+async function getEncoderBuilderResult (options: {
+ streamType: string
+ input: string
- /*
- MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
- Our target situation is closer to a livestream than a stream,
- since we want to reduce as much a possible the encoding burden,
- although not to the point of a livestream where there is a hard
- constraint on the frames per second to be encoded.
- */
+ availableEncoders: AvailableEncoders
+ profile: string
- return localCommand
+ videoType: 'vod' | 'live'
+
+ resolution: number
+ fps?: number
+ streamNum?: number
+}) {
+ const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
+
+ const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType]
+
+ for (const encoder of encodersToTry) {
+ if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue
+
+ const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder]
+ let builder = builderProfiles[profile]
+
+ if (!builder) {
+ logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
+ builder = builderProfiles.default
+ }
+
+ const result = await builder({ input, resolution: resolution, fps, streamNum })
+
+ return {
+ result,
+
+ // If we don't have output options, then copy the input stream
+ encoder: result.copy === true
+ ? 'copy'
+ : encoder
+ }
+ }
+
+ return null
}
-/**
- * Standard profile, with variable bitrate audio and faststart.
- *
- * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
- * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
- */
-async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
+async function presetVideo (
+ command: ffmpeg.FfmpegCommand,
+ input: string,
+ transcodeOptions: TranscodeOptions,
+ fps?: number
+) {
let localCommand = command
.format('mp4')
- .videoCodec('libx264')
.outputOption('-movflags faststart')
- addDefaultX264Params(localCommand)
+ addDefaultEncoderGlobalParams({ command })
+ // Audio encoder
const parsedAudio = await getAudioStream(input)
+ let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
+
if (!parsedAudio.audioStream) {
localCommand = localCommand.noAudio()
- } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
- localCommand = localCommand
- .audioCodec('libfdk_aac')
- .audioQuality(5)
- } else {
- // we try to reduce the ceiling bitrate by making rough matches of bitrates
- // of course this is far from perfect, but it might save some space in the end
- localCommand = localCommand.audioCodec('aac')
+ streamsToProcess = [ 'VIDEO' ]
+ }
+
+ for (const streamType of streamsToProcess) {
+ const { profile, resolution, availableEncoders } = transcodeOptions
+
+ const builderResult = await getEncoderBuilderResult({
+ streamType,
+ input,
+ resolution,
+ availableEncoders,
+ profile,
+ fps,
+ videoType: 'vod' as 'vod'
+ })
- const audioCodecName = parsedAudio.audioStream['codec_name']
+ if (!builderResult) {
+ throw new Error('No available encoder found for stream ' + streamType)
+ }
- const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
+ logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
- if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
- }
+ if (streamType === 'VIDEO') {
+ localCommand.videoCodec(builderResult.encoder)
+ } else if (streamType === 'AUDIO') {
+ localCommand.audioCodec(builderResult.encoder)
+ }
- if (fps) {
- // Constrained Encoding (VBV)
- // https://slhck.info/video/2017/03/01/rate-control.html
- // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
- const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
- localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
-
- // Keyframe interval of 2 seconds for faster seeking and resolution switching.
- // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
- // https://superuser.com/a/908325
- localCommand = localCommand.outputOption(`-g ${fps * 2}`)
+ command.addOutputOptions(builderResult.result.outputOptions)
+ addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
}
return localCommand
.noVideo()
}
+// ---------------------------------------------------------------------------
+// Utils
+// ---------------------------------------------------------------------------
+
function getFFmpeg (input: string) {
// We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
const command = ffmpeg(input, { niceness: FFMPEG_NICE.TRANSCODING, cwd: CONFIG.STORAGE.TMP_DIR })
return command
}
+
+async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
+ return new Promise<void>((res, rej) => {
+ command.on('error', (err, stdout, stderr) => {
+ if (onEnd) onEnd()
+
+ logger.error('Error in transcoding job.', { stdout, stderr })
+ rej(err)
+ })
+
+ command.on('end', () => {
+ if (onEnd) onEnd()
+
+ res()
+ })
+
+ command.run()
+ })
+}