From 9252a33d115bba85adcfbc18ab3725924642871c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 23 Nov 2020 16:23:52 +0100 Subject: [PATCH] Export encoders options in a dedicated struct --- server/helpers/ffmpeg-utils.ts | 346 ++++++++++++--------- server/initializers/checker-before-init.ts | 29 +- server/initializers/constants.ts | 12 + server/lib/live-manager.ts | 8 +- server/lib/video-transcoding.ts | 114 ++++++- 5 files changed, 341 insertions(+), 168 deletions(-) diff --git a/server/helpers/ffmpeg-utils.ts b/server/helpers/ffmpeg-utils.ts index df3926658..e297108df 100644 --- a/server/helpers/ffmpeg-utils.ts +++ b/server/helpers/ffmpeg-utils.ts @@ -4,11 +4,88 @@ import { dirname, join } from 'path' import { getTargetBitrate, 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 { FFMPEG_NICE, VIDEO_LIVE, VIDEO_TRANSCODING_ENCODERS, VIDEO_TRANSCODING_FPS } from '../initializers/constants' +import { getAudioStream, getClosestFramerateStandard, getVideoFileFPS } from './ffprobe-utils' import { processImage } from './image-utils' import { logger } from './logger' +// --------------------------------------------------------------------------- +// Encoder options +// --------------------------------------------------------------------------- + +// Options builders + +export type EncoderOptionsBuilder = (params: { + input: string + resolution: VideoResolution + fps?: number +}) => Promise | EncoderOptions + +// Options types + +export interface EncoderOptions { + outputOptions: string[] +} + +// All our encoders + +export interface EncoderProfile { + [ profile: string ]: T + + default: T +} + +export type AvailableEncoders = { + [ id in 'live' | 'vod' ]: { + [ encoder in 'libx264' | 'aac' | 'libfdkAAC' ]: EncoderProfile + } +} + +// --------------------------------------------------------------------------- +// Image manipulation +// --------------------------------------------------------------------------- + +function convertWebPToJPG (path: string, destination: string): Promise { + const command = ffmpeg(path) + .output(destination) + + return runCommand(command) +} + +function processGIF ( + path: string, + destination: string, + newSize: { width: number, height: number }, + keepOriginal = false +): Promise { + return new Promise(async (res, rej) => { + if (path === destination) { + throw new Error('FFmpeg needs an input path different that the output path.') + } + + logger.debug('Processing gif %s to %s.', path, destination) + + 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) + } + }) +} + async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) { const pendingImageName = 'pending-' + imageName @@ -49,9 +126,15 @@ type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio' interface BaseTranscodeOptions { type: TranscodeOptionsType + inputPath: string outputPath: string + + availableEncoders: AvailableEncoders + profile: string + resolution: VideoResolution + isPortraitMode?: boolean } @@ -94,7 +177,7 @@ const builders: { 'hls': buildHLSVODCommand, 'merge-audio': buildAudioMergeCommand, 'only-audio': buildOnlyAudioCommand, - 'video': buildx264Command + 'video': buildx264VODCommand } async function transcode (options: TranscodeOptions) { @@ -110,58 +193,11 @@ async function transcode (options: TranscodeOptions) { await fixHLSPlaylistIfNeeded(options) } -function convertWebPToJPG (path: string, destination: string): Promise { - return new Promise(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 { - return new Promise(async (res, rej) => { - if (path === destination) { - throw new Error('FFmpeg needs an input path different that the output path.') - } - - logger.debug('Processing gif %s to %s.', path, destination) - - 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) - } - }) -} +// --------------------------------------------------------------------------- +// Live muxing/transcoding functions +// --------------------------------------------------------------------------- -function runLiveTranscoding (rtmpUrl: string, outPath: string, resolutions: number[], fps, deleteSegments: boolean) { +function getLiveTranscodingCommand (rtmpUrl: string, outPath: string, resolutions: number[], fps: number, deleteSegments: boolean) { const command = getFFmpeg(rtmpUrl) command.inputOption('-fflags nobuffer') @@ -183,14 +219,9 @@ function runLiveTranscoding (rtmpUrl: string, outPath: string, resolutions: numb })) ]) - command.outputOption('-b_strategy 1') - command.outputOption('-bf 16') + addEncoderDefaultParams(command, 'libx264', fps) + 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)) for (let i = 0; i < resolutions.length; i++) { const resolution = resolutions[i] @@ -209,12 +240,10 @@ function runLiveTranscoding (rtmpUrl: string, outPath: string, resolutions: numb 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') @@ -225,8 +254,6 @@ function runLiveMuxing (rtmpUrl: string, outPath: string, deleteSegments: boolea addDefaultLiveHLSParams(command, outPath, deleteSegments) - command.run() - return command } @@ -255,32 +282,13 @@ async function hlsPlaylistToFragmentedMP4 (hlsDirectory: string, segmentFiles: s return runCommand(command, cleaner) } -async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) { - return new Promise((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() - }) -} - // --------------------------------------------------------------------------- export { - runLiveMuxing, + getLiveTranscodingCommand, + getLiveMuxingCommand, convertWebPToJPG, processGIF, - runLiveTranscoding, generateImageFromVideoFile, TranscodeOptions, TranscodeOptionsType, @@ -290,12 +298,23 @@ export { // --------------------------------------------------------------------------- -function addDefaultX264Params (command: ffmpeg.FfmpegCommand) { +// --------------------------------------------------------------------------- +// Default options +// --------------------------------------------------------------------------- + +function addEncoderDefaultParams (command: ffmpeg.FfmpegCommand, encoder: 'libx264' | string, fps?: number) { + if (encoder !== 'libx264') return + 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 + .outputOption('-max_muxing_queue_size 1024') // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375 + // 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 + .outputOption('-g ' + (fps * 2)) } function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, deleteSegments: boolean) { @@ -313,7 +332,11 @@ function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string 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 @@ -325,7 +348,7 @@ async function buildx264Command (command: ffmpeg.FfmpegCommand, options: Transco fps = getClosestFramerateStandard(fps, 'STANDARD') } - 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 @@ -347,7 +370,16 @@ async function buildx264Command (command: ffmpeg.FfmpegCommand, options: Transco 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) + + /* + 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. + */ + 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 @@ -377,7 +409,7 @@ async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTr 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') @@ -390,10 +422,6 @@ async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTr return command } -function getHLSVideoPath (options: HLSTranscodeOptions) { - return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}` -} - async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) { if (options.type !== 'hls') return @@ -409,76 +437,71 @@ async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) { 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) - - localCommand = localCommand.outputOption('-preset:v veryfast') - - /* - 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. - */ - - return localCommand +function getHLSVideoPath (options: HLSTranscodeOptions) { + return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}` } -/** - * 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) { +// --------------------------------------------------------------------------- +// Transcoding presets +// --------------------------------------------------------------------------- + +async function presetVideo ( + command: ffmpeg.FfmpegCommand, + input: string, + transcodeOptions: TranscodeOptions, + fps?: number +) { let localCommand = command .format('mp4') - .videoCodec('libx264') .outputOption('-movflags faststart') - addDefaultX264Params(localCommand) - + // Audio encoder const parsedAudio = await getAudioStream(input) + let streamsToProcess = [ 'AUDIO', 'VIDEO' ] + const streamsFound = { + 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' ] + } - const audioCodecName = parsedAudio.audioStream['codec_name'] + for (const stream of streamsToProcess) { + const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[stream] - const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate) + for (const encoder of encodersToTry) { + if (!(await checkFFmpegEncoders()).get(encoder)) continue - if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate) - } + const builderProfiles: EncoderProfile = transcodeOptions.availableEncoders.vod[encoder] + let builder = builderProfiles[transcodeOptions.profile] - 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}`) + if (!builder) { + logger.debug('Profile %s for encoder %s not available. Fallback to default.', transcodeOptions.profile, encoder) + builder = builderProfiles.default + } + + const builderResult = await builder({ input, resolution: transcodeOptions.resolution, fps }) + + logger.debug('Apply ffmpeg params from %s.', encoder, builderResult) + + localCommand.outputOptions(builderResult.outputOptions) + + addEncoderDefaultParams(localCommand, encoder) + + streamsFound[stream] = encoder + break + } + + if (!streamsFound[stream]) { + throw new Error('No available encoder found ' + encodersToTry.join(', ')) + } } + localCommand.videoCodec(streamsFound.VIDEO) + return localCommand } @@ -496,6 +519,10 @@ function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand { .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 }) @@ -507,3 +534,22 @@ function getFFmpeg (input: string) { return command } + +async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) { + return new Promise((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() + }) +} diff --git a/server/initializers/checker-before-init.ts b/server/initializers/checker-before-init.ts index 93b71a242..4ffd6fad9 100644 --- a/server/initializers/checker-before-init.ts +++ b/server/initializers/checker-before-init.ts @@ -82,6 +82,8 @@ function checkMissedConfig () { async function checkFFmpeg (CONFIG: { TRANSCODING: { ENABLED: boolean } }) { if (CONFIG.TRANSCODING.ENABLED === false) return undefined + checkFFmpegEncoders() + const Ffmpeg = require('fluent-ffmpeg') const getAvailableCodecsPromise = promisify0(Ffmpeg.getAvailableCodecs) const codecs = await getAvailableCodecsPromise() @@ -100,25 +102,30 @@ async function checkFFmpeg (CONFIG: { TRANSCODING: { ENABLED: boolean } }) { return checkFFmpegEncoders() } -// Optional encoders, if present, can be used to improve transcoding -// Here we ask ffmpeg if it detects their presence on the system, so that we can later use them -let supportedOptionalEncoders: Map +// Detect supported encoders by ffmpeg +let supportedEncoders: Map async function checkFFmpegEncoders (): Promise> { - if (supportedOptionalEncoders !== undefined) { - return supportedOptionalEncoders + if (supportedEncoders !== undefined) { + return supportedEncoders } const Ffmpeg = require('fluent-ffmpeg') const getAvailableEncodersPromise = promisify0(Ffmpeg.getAvailableEncoders) - const encoders = await getAvailableEncodersPromise() - const optionalEncoders = [ 'libfdk_aac' ] - supportedOptionalEncoders = new Map() + const availableEncoders = await getAvailableEncodersPromise() + + const searchEncoders = [ + 'aac', + 'libfdk_aac', + 'libx264' + ] + + supportedEncoders = new Map() - for (const encoder of optionalEncoders) { - supportedOptionalEncoders.set(encoder, encoders[encoder] !== undefined) + for (const searchEncoder of searchEncoders) { + supportedEncoders.set(searchEncoder, availableEncoders[searchEncoder] !== undefined) } - return supportedOptionalEncoders + return supportedEncoders } function checkNodeVersion () { diff --git a/server/initializers/constants.ts b/server/initializers/constants.ts index 5c6d06077..945185f62 100644 --- a/server/initializers/constants.ts +++ b/server/initializers/constants.ts @@ -336,6 +336,17 @@ const VIDEO_TRANSCODING_FPS: VideoTranscodingFPS = { KEEP_ORIGIN_FPS_RESOLUTION_MIN: 720 // We keep the original FPS on high resolutions (720 minimum) } +const VIDEO_TRANSCODING_ENCODERS = { + VIDEO: [ 'libx264' ], + + // Try the first one, if not available try the second one etc + AUDIO: [ + // we favor VBR, if a good AAC encoder is available + 'libfdk_aac', + 'aac' + ] +} + const DEFAULT_AUDIO_RESOLUTION = VideoResolution.H_480P const VIDEO_RATE_TYPES: { [ id: string ]: VideoRateType } = { @@ -804,6 +815,7 @@ export { ACTOR_FOLLOW_SCORE, PREVIEWS_SIZE, REMOTE_SCHEME, + VIDEO_TRANSCODING_ENCODERS, FOLLOW_STATES, DEFAULT_USER_THEME_NAME, SERVER_ACTOR_NAME, diff --git a/server/lib/live-manager.ts b/server/lib/live-manager.ts index 4d2e9b1b3..b9e5d4561 100644 --- a/server/lib/live-manager.ts +++ b/server/lib/live-manager.ts @@ -4,7 +4,7 @@ import { FfmpegCommand } from 'fluent-ffmpeg' import { ensureDir, stat } from 'fs-extra' import { basename } from 'path' import { isTestInstance } from '@server/helpers/core-utils' -import { runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils' +import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils' import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils' import { logger } from '@server/helpers/logger' import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' @@ -264,8 +264,8 @@ class LiveManager { const deleteSegments = videoLive.saveReplay === false const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED - ? runLiveTranscoding(rtmpUrl, outPath, allResolutions, fps, deleteSegments) - : runLiveMuxing(rtmpUrl, outPath, deleteSegments) + ? getLiveTranscodingCommand(rtmpUrl, outPath, allResolutions, fps, deleteSegments) + : getLiveMuxingCommand(rtmpUrl, outPath, deleteSegments) logger.info('Running live muxing/transcoding for %s.', videoUUID) this.transSessions.set(sessionId, ffmpegExec) @@ -382,6 +382,8 @@ class LiveManager { }) ffmpegExec.on('end', () => onFFmpegEnded()) + + ffmpegExec.run() } private async onEndTransmuxing (videoId: number, cleanupNow = false) { diff --git a/server/lib/video-transcoding.ts b/server/lib/video-transcoding.ts index ca969b235..0e6a0e984 100644 --- a/server/lib/video-transcoding.ts +++ b/server/lib/video-transcoding.ts @@ -2,13 +2,26 @@ import { copyFile, ensureDir, move, remove, stat } from 'fs-extra' import { basename, extname as extnameUtil, join } from 'path' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models' -import { VideoResolution } from '../../shared/models/videos' +import { getTargetBitrate, VideoResolution } from '../../shared/models/videos' import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type' -import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils' -import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils' +import { AvailableEncoders, EncoderOptionsBuilder, transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils' +import { + canDoQuickTranscode, + getAudioStream, + getDurationFromVideoFile, + getMaxAudioBitrate, + getMetadataFromFile, + getVideoFileBitrate, + getVideoFileFPS +} from '../helpers/ffprobe-utils' import { logger } from '../helpers/logger' import { CONFIG } from '../initializers/config' -import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants' +import { + HLS_STREAMING_PLAYLIST_DIRECTORY, + P2P_MEDIA_LOADER_PEER_VERSION, + VIDEO_TRANSCODING_FPS, + WEBSERVER +} from '../initializers/constants' import { VideoFileModel } from '../models/video/video-file' import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist' import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls' @@ -31,8 +44,13 @@ async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileA const transcodeOptions: TranscodeOptions = { type: transcodeType, + inputPath: videoInputPath, outputPath: videoTranscodedPath, + + availableEncoders, + profile: 'default', + resolution: inputVideoFile.resolution } @@ -78,14 +96,23 @@ async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoR const transcodeOptions = resolution === VideoResolution.H_NOVIDEO ? { type: 'only-audio' as 'only-audio', + inputPath: videoInputPath, outputPath: videoTranscodedPath, + + availableEncoders, + profile: 'default', + resolution } : { type: 'video' as 'video', inputPath: videoInputPath, outputPath: videoTranscodedPath, + + availableEncoders, + profile: 'default', + resolution, isPortraitMode: isPortrait } @@ -111,8 +138,13 @@ async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: Video const transcodeOptions = { type: 'merge-audio' as 'merge-audio', + inputPath: tmpPreviewPath, outputPath: videoTranscodedPath, + + availableEncoders, + profile: 'default', + audioPath: audioInputPath, resolution } @@ -156,8 +188,13 @@ async function generateHlsPlaylist (options: { const transcodeOptions = { type: 'hls' as 'hls', + inputPath: videoInputPath, outputPath, + + availableEncoders, + profile: 'default', + resolution, copyCodecs, isPortraitMode, @@ -215,6 +252,75 @@ async function generateHlsPlaylist (options: { return video } +// --------------------------------------------------------------------------- +// Available encoders profiles +// --------------------------------------------------------------------------- + +const defaultX264OptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => { + if (!fps) return { outputOptions: [] } + + let targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS) + + // Don't transcode to an higher bitrate than the original file + const fileBitrate = await getVideoFileBitrate(input) + targetBitrate = Math.min(targetBitrate, fileBitrate) + + return { + outputOptions: [ + // Constrained Encoding (VBV) + // https://slhck.info/video/2017/03/01/rate-control.html + // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate + `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` + ] + } +} + +const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input }) => { + const parsedAudio = await getAudioStream(input) + + // 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 + + const audioCodecName = parsedAudio.audioStream['codec_name'] + + const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate) + + if (bitrate !== undefined && bitrate !== -1) { + return { outputOptions: [ '-b:a', bitrate + 'k' ] } + } + + return { outputOptions: [] } +} + +const defaultLibFDKAACOptionsBuilder: EncoderOptionsBuilder = () => { + return { outputOptions: [ '-aq', '5' ] } +} + +const availableEncoders: AvailableEncoders = { + vod: { + libx264: { + default: defaultX264OptionsBuilder + }, + aac: { + default: defaultAACOptionsBuilder + }, + libfdkAAC: { + default: defaultLibFDKAACOptionsBuilder + } + }, + live: { + libx264: { + default: defaultX264OptionsBuilder + }, + aac: { + default: defaultAACOptionsBuilder + }, + libfdkAAC: { + default: defaultLibFDKAACOptionsBuilder + } + } +} + // --------------------------------------------------------------------------- export { -- 2.41.0