Improve target bitrate calculation
This commit is contained in:
parent
c826f34a45
commit
679c12e69c
|
@ -47,13 +47,13 @@ async function run () {
|
||||||
if (!video) throw new Error('Video not found.')
|
if (!video) throw new Error('Video not found.')
|
||||||
|
|
||||||
const dataInput: VideoTranscodingPayload[] = []
|
const dataInput: VideoTranscodingPayload[] = []
|
||||||
const { videoFileResolution } = await video.getMaxQualityResolution()
|
const { resolution } = await video.getMaxQualityResolution()
|
||||||
|
|
||||||
// Generate HLS files
|
// Generate HLS files
|
||||||
if (options.generateHls || CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
|
if (options.generateHls || CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) {
|
||||||
const resolutionsEnabled = options.resolution
|
const resolutionsEnabled = options.resolution
|
||||||
? [ options.resolution ]
|
? [ options.resolution ]
|
||||||
: computeResolutionsToTranscode(videoFileResolution, 'vod').concat([ videoFileResolution ])
|
: computeResolutionsToTranscode(resolution, 'vod').concat([ resolution ])
|
||||||
|
|
||||||
for (const resolution of resolutionsEnabled) {
|
for (const resolution of resolutionsEnabled) {
|
||||||
dataInput.push({
|
dataInput.push({
|
||||||
|
|
|
@ -1,9 +1,7 @@
|
||||||
import { registerTSPaths } from '../server/helpers/register-ts-paths'
|
import { registerTSPaths } from '../server/helpers/register-ts-paths'
|
||||||
registerTSPaths()
|
registerTSPaths()
|
||||||
|
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../server/initializers/constants'
|
|
||||||
import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffprobe-utils'
|
import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffprobe-utils'
|
||||||
import { getMaxBitrate } from '../shared/models/videos'
|
|
||||||
import { VideoModel } from '../server/models/video/video'
|
import { VideoModel } from '../server/models/video/video'
|
||||||
import { optimizeOriginalVideofile } from '../server/lib/transcoding/video-transcoding'
|
import { optimizeOriginalVideofile } from '../server/lib/transcoding/video-transcoding'
|
||||||
import { initDatabaseModels } from '../server/initializers/database'
|
import { initDatabaseModels } from '../server/initializers/database'
|
||||||
|
@ -11,6 +9,7 @@ import { basename, dirname } from 'path'
|
||||||
import { copy, move, remove } from 'fs-extra'
|
import { copy, move, remove } from 'fs-extra'
|
||||||
import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
|
import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
|
||||||
import { getVideoFilePath } from '@server/lib/video-paths'
|
import { getVideoFilePath } from '@server/lib/video-paths'
|
||||||
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
|
|
||||||
run()
|
run()
|
||||||
.then(() => process.exit(0))
|
.then(() => process.exit(0))
|
||||||
|
@ -42,13 +41,13 @@ async function run () {
|
||||||
for (const file of video.VideoFiles) {
|
for (const file of video.VideoFiles) {
|
||||||
currentFilePath = getVideoFilePath(video, file)
|
currentFilePath = getVideoFilePath(video, file)
|
||||||
|
|
||||||
const [ videoBitrate, fps, resolution ] = await Promise.all([
|
const [ videoBitrate, fps, dataResolution ] = await Promise.all([
|
||||||
getVideoFileBitrate(currentFilePath),
|
getVideoFileBitrate(currentFilePath),
|
||||||
getVideoFileFPS(currentFilePath),
|
getVideoFileFPS(currentFilePath),
|
||||||
getVideoFileResolution(currentFilePath)
|
getVideoFileResolution(currentFilePath)
|
||||||
])
|
])
|
||||||
|
|
||||||
const maxBitrate = getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)
|
const maxBitrate = getMaxBitrate({ ...dataResolution, fps })
|
||||||
const isMaxBitrateExceeded = videoBitrate > maxBitrate
|
const isMaxBitrateExceeded = videoBitrate > maxBitrate
|
||||||
if (isMaxBitrateExceeded) {
|
if (isMaxBitrateExceeded) {
|
||||||
console.log(
|
console.log(
|
||||||
|
|
|
@ -239,7 +239,7 @@ async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUplo
|
||||||
videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
|
videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
|
||||||
} else {
|
} else {
|
||||||
videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
|
videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
|
||||||
videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
|
videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution
|
||||||
}
|
}
|
||||||
|
|
||||||
videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
|
videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
|
||||||
|
|
|
@ -3,10 +3,18 @@ import * as ffmpeg from 'fluent-ffmpeg'
|
||||||
import { readFile, remove, writeFile } from 'fs-extra'
|
import { readFile, remove, writeFile } from 'fs-extra'
|
||||||
import { dirname, join } from 'path'
|
import { dirname, join } from 'path'
|
||||||
import { FFMPEG_NICE, VIDEO_LIVE } from '@server/initializers/constants'
|
import { FFMPEG_NICE, VIDEO_LIVE } from '@server/initializers/constants'
|
||||||
import { AvailableEncoders, EncoderOptions, EncoderOptionsBuilder, EncoderProfile, VideoResolution } from '../../shared/models/videos'
|
import { pick } from '@shared/core-utils'
|
||||||
|
import {
|
||||||
|
AvailableEncoders,
|
||||||
|
EncoderOptions,
|
||||||
|
EncoderOptionsBuilder,
|
||||||
|
EncoderOptionsBuilderParams,
|
||||||
|
EncoderProfile,
|
||||||
|
VideoResolution
|
||||||
|
} from '../../shared/models/videos'
|
||||||
import { CONFIG } from '../initializers/config'
|
import { CONFIG } from '../initializers/config'
|
||||||
import { execPromise, promisify0 } from './core-utils'
|
import { execPromise, promisify0 } from './core-utils'
|
||||||
import { computeFPS, ffprobePromise, getAudioStream, getVideoFileBitrate, getVideoFileFPS } from './ffprobe-utils'
|
import { computeFPS, ffprobePromise, getAudioStream, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from './ffprobe-utils'
|
||||||
import { processImage } from './image-utils'
|
import { processImage } from './image-utils'
|
||||||
import { logger } from './logger'
|
import { logger } from './logger'
|
||||||
|
|
||||||
|
@ -217,13 +225,16 @@ async function getLiveTranscodingCommand (options: {
|
||||||
masterPlaylistName: string
|
masterPlaylistName: string
|
||||||
|
|
||||||
resolutions: number[]
|
resolutions: number[]
|
||||||
|
|
||||||
|
// Input information
|
||||||
fps: number
|
fps: number
|
||||||
bitrate: number
|
bitrate: number
|
||||||
|
ratio: number
|
||||||
|
|
||||||
availableEncoders: AvailableEncoders
|
availableEncoders: AvailableEncoders
|
||||||
profile: string
|
profile: string
|
||||||
}) {
|
}) {
|
||||||
const { rtmpUrl, outPath, resolutions, fps, bitrate, availableEncoders, profile, masterPlaylistName } = options
|
const { rtmpUrl, outPath, resolutions, fps, bitrate, availableEncoders, profile, masterPlaylistName, ratio } = options
|
||||||
const input = rtmpUrl
|
const input = rtmpUrl
|
||||||
|
|
||||||
const command = getFFmpeg(input, 'live')
|
const command = getFFmpeg(input, 'live')
|
||||||
|
@ -253,9 +264,12 @@ async function getLiveTranscodingCommand (options: {
|
||||||
availableEncoders,
|
availableEncoders,
|
||||||
profile,
|
profile,
|
||||||
|
|
||||||
fps: resolutionFPS,
|
|
||||||
inputBitrate: bitrate,
|
inputBitrate: bitrate,
|
||||||
|
inputRatio: ratio,
|
||||||
|
|
||||||
resolution,
|
resolution,
|
||||||
|
fps: resolutionFPS,
|
||||||
|
|
||||||
streamNum: i,
|
streamNum: i,
|
||||||
videoType: 'live' as 'live'
|
videoType: 'live' as 'live'
|
||||||
}
|
}
|
||||||
|
@ -502,7 +516,7 @@ function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptio
|
||||||
// Run encoder builder depending on available encoders
|
// Run encoder builder depending on available encoders
|
||||||
// Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
|
// Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
|
||||||
// If the default one does not exist, check the next encoder
|
// If the default one does not exist, check the next encoder
|
||||||
async function getEncoderBuilderResult (options: {
|
async function getEncoderBuilderResult (options: EncoderOptionsBuilderParams & {
|
||||||
streamType: 'video' | 'audio'
|
streamType: 'video' | 'audio'
|
||||||
input: string
|
input: string
|
||||||
|
|
||||||
|
@ -510,13 +524,8 @@ async function getEncoderBuilderResult (options: {
|
||||||
profile: string
|
profile: string
|
||||||
|
|
||||||
videoType: 'vod' | 'live'
|
videoType: 'vod' | 'live'
|
||||||
|
|
||||||
resolution: number
|
|
||||||
inputBitrate: number
|
|
||||||
fps?: number
|
|
||||||
streamNum?: number
|
|
||||||
}) {
|
}) {
|
||||||
const { availableEncoders, input, profile, resolution, streamType, fps, inputBitrate, streamNum, videoType } = options
|
const { availableEncoders, profile, streamType, videoType } = options
|
||||||
|
|
||||||
const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
|
const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
|
||||||
const encoders = availableEncoders.available[videoType]
|
const encoders = availableEncoders.available[videoType]
|
||||||
|
@ -546,7 +555,7 @@ async function getEncoderBuilderResult (options: {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await builder({ input, resolution, inputBitrate, fps, streamNum })
|
const result = await builder(pick(options, [ 'input', 'resolution', 'inputBitrate', 'fps', 'inputRatio', 'streamNum' ]))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
result,
|
result,
|
||||||
|
@ -581,6 +590,7 @@ async function presetVideo (options: {
|
||||||
// Audio encoder
|
// Audio encoder
|
||||||
const parsedAudio = await getAudioStream(input, probe)
|
const parsedAudio = await getAudioStream(input, probe)
|
||||||
const bitrate = await getVideoFileBitrate(input, probe)
|
const bitrate = await getVideoFileBitrate(input, probe)
|
||||||
|
const { ratio } = await getVideoFileResolution(input, probe)
|
||||||
|
|
||||||
let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
|
let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
|
||||||
|
|
||||||
|
@ -600,6 +610,7 @@ async function presetVideo (options: {
|
||||||
profile,
|
profile,
|
||||||
fps,
|
fps,
|
||||||
inputBitrate: bitrate,
|
inputBitrate: bitrate,
|
||||||
|
inputRatio: ratio,
|
||||||
videoType: 'vod' as 'vod'
|
videoType: 'vod' as 'vod'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
import * as ffmpeg from 'fluent-ffmpeg'
|
import * as ffmpeg from 'fluent-ffmpeg'
|
||||||
import { getMaxBitrate, VideoFileMetadata, VideoResolution } from '../../shared/models/videos'
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
|
import { VideoFileMetadata, VideoResolution, VideoTranscodingFPS } from '../../shared/models/videos'
|
||||||
import { CONFIG } from '../initializers/config'
|
import { CONFIG } from '../initializers/config'
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
|
import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
|
||||||
import { logger } from './logger'
|
import { logger } from './logger'
|
||||||
|
@ -75,7 +76,7 @@ function getMaxAudioBitrate (type: 'aac' | 'mp3' | string, bitrate: number) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getVideoStreamSize (path: string, existingProbe?: ffmpeg.FfprobeData) {
|
async function getVideoStreamSize (path: string, existingProbe?: ffmpeg.FfprobeData): Promise<{ width: number, height: number }> {
|
||||||
const videoStream = await getVideoStreamFromFile(path, existingProbe)
|
const videoStream = await getVideoStreamFromFile(path, existingProbe)
|
||||||
|
|
||||||
return videoStream === null
|
return videoStream === null
|
||||||
|
@ -146,7 +147,10 @@ async function getVideoFileResolution (path: string, existingProbe?: ffmpeg.Ffpr
|
||||||
const size = await getVideoStreamSize(path, existingProbe)
|
const size = await getVideoStreamSize(path, existingProbe)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
videoFileResolution: Math.min(size.height, size.width),
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
ratio: Math.max(size.height, size.width) / Math.min(size.height, size.width),
|
||||||
|
resolution: Math.min(size.height, size.width),
|
||||||
isPortraitMode: size.height > size.width
|
isPortraitMode: size.height > size.width
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -243,7 +247,7 @@ async function canDoQuickVideoTranscode (path: string, probe?: ffmpeg.FfprobeDat
|
||||||
const videoStream = await getVideoStreamFromFile(path, probe)
|
const videoStream = await getVideoStreamFromFile(path, probe)
|
||||||
const fps = await getVideoFileFPS(path, probe)
|
const fps = await getVideoFileFPS(path, probe)
|
||||||
const bitRate = await getVideoFileBitrate(path, probe)
|
const bitRate = await getVideoFileBitrate(path, probe)
|
||||||
const resolution = await getVideoFileResolution(path, probe)
|
const resolutionData = await getVideoFileResolution(path, probe)
|
||||||
|
|
||||||
// If ffprobe did not manage to guess the bitrate
|
// If ffprobe did not manage to guess the bitrate
|
||||||
if (!bitRate) return false
|
if (!bitRate) return false
|
||||||
|
@ -253,7 +257,7 @@ async function canDoQuickVideoTranscode (path: string, probe?: ffmpeg.FfprobeDat
|
||||||
if (videoStream['codec_name'] !== 'h264') return false
|
if (videoStream['codec_name'] !== 'h264') return false
|
||||||
if (videoStream['pix_fmt'] !== 'yuv420p') return false
|
if (videoStream['pix_fmt'] !== 'yuv420p') return false
|
||||||
if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
|
if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
|
||||||
if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
|
if (bitRate > getMaxBitrate({ ...resolutionData, fps })) return false
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
@ -278,7 +282,7 @@ async function canDoQuickAudioTranscode (path: string, probe?: ffmpeg.FfprobeDat
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
function getClosestFramerateStandard (fps: number, type: 'HD_STANDARD' | 'STANDARD'): number {
|
function getClosestFramerateStandard <K extends keyof Pick<VideoTranscodingFPS, 'HD_STANDARD' | 'STANDARD'>> (fps: number, type: K) {
|
||||||
return VIDEO_TRANSCODING_FPS[type].slice(0)
|
return VIDEO_TRANSCODING_FPS[type].slice(0)
|
||||||
.sort((a, b) => fps % a - fps % b)[0]
|
.sort((a, b) => fps % a - fps % b)[0]
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,17 +27,15 @@ function up (utils: {
|
||||||
const ext = matches[2]
|
const ext = matches[2]
|
||||||
|
|
||||||
const p = getVideoFileResolution(join(videoFileDir, videoFile))
|
const p = getVideoFileResolution(join(videoFileDir, videoFile))
|
||||||
.then(height => {
|
.then(async ({ resolution }) => {
|
||||||
const oldTorrentName = uuid + '.torrent'
|
const oldTorrentName = uuid + '.torrent'
|
||||||
const newTorrentName = uuid + '-' + height + '.torrent'
|
const newTorrentName = uuid + '-' + resolution + '.torrent'
|
||||||
return rename(join(torrentDir, oldTorrentName), join(torrentDir, newTorrentName)).then(() => height)
|
await rename(join(torrentDir, oldTorrentName), join(torrentDir, newTorrentName)).then(() => resolution)
|
||||||
})
|
|
||||||
.then(height => {
|
const newVideoFileName = uuid + '-' + resolution + '.' + ext
|
||||||
const newVideoFileName = uuid + '-' + height + '.' + ext
|
await rename(join(videoFileDir, videoFile), join(videoFileDir, newVideoFileName)).then(() => resolution)
|
||||||
return rename(join(videoFileDir, videoFile), join(videoFileDir, newVideoFileName)).then(() => height)
|
|
||||||
})
|
const query = 'UPDATE "VideoFiles" SET "resolution" = ' + resolution +
|
||||||
.then(height => {
|
|
||||||
const query = 'UPDATE "VideoFiles" SET "resolution" = ' + height +
|
|
||||||
' WHERE "videoId" = (SELECT "id" FROM "Videos" WHERE "uuid" = \'' + uuid + '\')'
|
' WHERE "videoId" = (SELECT "id" FROM "Videos" WHERE "uuid" = \'' + uuid + '\')'
|
||||||
return utils.sequelize.query(query)
|
return utils.sequelize.query(query)
|
||||||
})
|
})
|
||||||
|
|
|
@ -32,7 +32,7 @@ async function processVideoFileImport (job: Bull.Job) {
|
||||||
const newResolutionPayload = {
|
const newResolutionPayload = {
|
||||||
type: 'new-resolution-to-webtorrent' as 'new-resolution-to-webtorrent',
|
type: 'new-resolution-to-webtorrent' as 'new-resolution-to-webtorrent',
|
||||||
videoUUID: video.uuid,
|
videoUUID: video.uuid,
|
||||||
resolution: data.videoFileResolution,
|
resolution: data.resolution,
|
||||||
isPortraitMode: data.isPortraitMode,
|
isPortraitMode: data.isPortraitMode,
|
||||||
copyCodecs: false,
|
copyCodecs: false,
|
||||||
isNewVideo: false
|
isNewVideo: false
|
||||||
|
@ -51,13 +51,13 @@ export {
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
|
async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
|
||||||
const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
|
const { resolution } = await getVideoFileResolution(inputFilePath)
|
||||||
const { size } = await stat(inputFilePath)
|
const { size } = await stat(inputFilePath)
|
||||||
const fps = await getVideoFileFPS(inputFilePath)
|
const fps = await getVideoFileFPS(inputFilePath)
|
||||||
|
|
||||||
const fileExt = getLowercaseExtension(inputFilePath)
|
const fileExt = getLowercaseExtension(inputFilePath)
|
||||||
|
|
||||||
const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === videoFileResolution)
|
const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === resolution)
|
||||||
|
|
||||||
if (currentVideoFile) {
|
if (currentVideoFile) {
|
||||||
// Remove old file and old torrent
|
// Remove old file and old torrent
|
||||||
|
@ -69,9 +69,9 @@ async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const newVideoFile = new VideoFileModel({
|
const newVideoFile = new VideoFileModel({
|
||||||
resolution: videoFileResolution,
|
resolution,
|
||||||
extname: fileExt,
|
extname: fileExt,
|
||||||
filename: generateWebTorrentVideoFilename(videoFileResolution, fileExt),
|
filename: generateWebTorrentVideoFilename(resolution, fileExt),
|
||||||
size,
|
size,
|
||||||
fps,
|
fps,
|
||||||
videoId: video.id
|
videoId: video.id
|
||||||
|
|
|
@ -114,7 +114,7 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid
|
||||||
throw new Error('The user video quota is exceeded with this video to import.')
|
throw new Error('The user video quota is exceeded with this video to import.')
|
||||||
}
|
}
|
||||||
|
|
||||||
const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
|
const { resolution } = await getVideoFileResolution(tempVideoPath)
|
||||||
const fps = await getVideoFileFPS(tempVideoPath)
|
const fps = await getVideoFileFPS(tempVideoPath)
|
||||||
const duration = await getDurationFromVideoFile(tempVideoPath)
|
const duration = await getDurationFromVideoFile(tempVideoPath)
|
||||||
|
|
||||||
|
@ -122,9 +122,9 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid
|
||||||
const fileExt = getLowercaseExtension(tempVideoPath)
|
const fileExt = getLowercaseExtension(tempVideoPath)
|
||||||
const videoFileData = {
|
const videoFileData = {
|
||||||
extname: fileExt,
|
extname: fileExt,
|
||||||
resolution: videoFileResolution,
|
resolution,
|
||||||
size: stats.size,
|
size: stats.size,
|
||||||
filename: generateWebTorrentVideoFilename(videoFileResolution, fileExt),
|
filename: generateWebTorrentVideoFilename(resolution, fileExt),
|
||||||
fps,
|
fps,
|
||||||
videoId: videoImport.videoId
|
videoId: videoImport.videoId
|
||||||
}
|
}
|
||||||
|
|
|
@ -96,12 +96,12 @@ async function saveLive (video: MVideo, live: MVideoLive, streamingPlaylist: MSt
|
||||||
const probe = await ffprobePromise(concatenatedTsFilePath)
|
const probe = await ffprobePromise(concatenatedTsFilePath)
|
||||||
const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
|
const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
|
||||||
|
|
||||||
const { videoFileResolution, isPortraitMode } = await getVideoFileResolution(concatenatedTsFilePath, probe)
|
const { resolution, isPortraitMode } = await getVideoFileResolution(concatenatedTsFilePath, probe)
|
||||||
|
|
||||||
const outputPath = await generateHlsPlaylistResolutionFromTS({
|
const outputPath = await generateHlsPlaylistResolutionFromTS({
|
||||||
video: videoWithFiles,
|
video: videoWithFiles,
|
||||||
concatenatedTsFilePath,
|
concatenatedTsFilePath,
|
||||||
resolution: videoFileResolution,
|
resolution,
|
||||||
isPortraitMode,
|
isPortraitMode,
|
||||||
isAAC: audioStream?.codec_name === 'aac'
|
isAAC: audioStream?.codec_name === 'aac'
|
||||||
})
|
})
|
||||||
|
|
|
@ -136,7 +136,7 @@ async function onVideoFileOptimizer (
|
||||||
if (videoArg === undefined) return undefined
|
if (videoArg === undefined) return undefined
|
||||||
|
|
||||||
// Outside the transaction (IO on disk)
|
// Outside the transaction (IO on disk)
|
||||||
const { videoFileResolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
|
const { resolution, isPortraitMode } = await videoArg.getMaxQualityResolution()
|
||||||
|
|
||||||
// Maybe the video changed in database, refresh it
|
// Maybe the video changed in database, refresh it
|
||||||
const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid)
|
const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid)
|
||||||
|
@ -155,7 +155,7 @@ async function onVideoFileOptimizer (
|
||||||
})
|
})
|
||||||
const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
|
const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload)
|
||||||
|
|
||||||
const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, videoFileResolution, isPortraitMode, 'webtorrent')
|
const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, resolution, isPortraitMode, 'webtorrent')
|
||||||
|
|
||||||
if (!hasHls && !hasNewResolutions) {
|
if (!hasHls && !hasNewResolutions) {
|
||||||
// No transcoding to do, it's now published
|
// No transcoding to do, it's now published
|
||||||
|
|
|
@ -202,7 +202,7 @@ class LiveManager {
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const probe = await ffprobePromise(rtmpUrl)
|
const probe = await ffprobePromise(rtmpUrl)
|
||||||
|
|
||||||
const [ { videoFileResolution }, fps, bitrate ] = await Promise.all([
|
const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
|
||||||
getVideoFileResolution(rtmpUrl, probe),
|
getVideoFileResolution(rtmpUrl, probe),
|
||||||
getVideoFileFPS(rtmpUrl, probe),
|
getVideoFileFPS(rtmpUrl, probe),
|
||||||
getVideoFileBitrate(rtmpUrl, probe)
|
getVideoFileBitrate(rtmpUrl, probe)
|
||||||
|
@ -210,13 +210,13 @@ class LiveManager {
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
'%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
|
'%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
|
||||||
rtmpUrl, Date.now() - now, bitrate, fps, videoFileResolution, lTags(sessionId, video.uuid)
|
rtmpUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
|
||||||
)
|
)
|
||||||
|
|
||||||
const allResolutions = this.buildAllResolutionsToTranscode(videoFileResolution)
|
const allResolutions = this.buildAllResolutionsToTranscode(resolution)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
'Will mux/transcode live video of original resolution %d.', videoFileResolution,
|
'Will mux/transcode live video of original resolution %d.', resolution,
|
||||||
{ allResolutions, ...lTags(sessionId, video.uuid) }
|
{ allResolutions, ...lTags(sessionId, video.uuid) }
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -229,6 +229,7 @@ class LiveManager {
|
||||||
rtmpUrl,
|
rtmpUrl,
|
||||||
fps,
|
fps,
|
||||||
bitrate,
|
bitrate,
|
||||||
|
ratio,
|
||||||
allResolutions
|
allResolutions
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -240,9 +241,10 @@ class LiveManager {
|
||||||
rtmpUrl: string
|
rtmpUrl: string
|
||||||
fps: number
|
fps: number
|
||||||
bitrate: number
|
bitrate: number
|
||||||
|
ratio: number
|
||||||
allResolutions: number[]
|
allResolutions: number[]
|
||||||
}) {
|
}) {
|
||||||
const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, rtmpUrl } = options
|
const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, rtmpUrl } = options
|
||||||
const videoUUID = videoLive.Video.uuid
|
const videoUUID = videoLive.Video.uuid
|
||||||
const localLTags = lTags(sessionId, videoUUID)
|
const localLTags = lTags(sessionId, videoUUID)
|
||||||
|
|
||||||
|
@ -257,6 +259,7 @@ class LiveManager {
|
||||||
streamingPlaylist,
|
streamingPlaylist,
|
||||||
rtmpUrl,
|
rtmpUrl,
|
||||||
bitrate,
|
bitrate,
|
||||||
|
ratio,
|
||||||
fps,
|
fps,
|
||||||
allResolutions
|
allResolutions
|
||||||
})
|
})
|
||||||
|
|
|
@ -54,9 +54,11 @@ class MuxingSession extends EventEmitter {
|
||||||
private readonly streamingPlaylist: MStreamingPlaylistVideo
|
private readonly streamingPlaylist: MStreamingPlaylistVideo
|
||||||
private readonly rtmpUrl: string
|
private readonly rtmpUrl: string
|
||||||
private readonly fps: number
|
private readonly fps: number
|
||||||
private readonly bitrate: number
|
|
||||||
private readonly allResolutions: number[]
|
private readonly allResolutions: number[]
|
||||||
|
|
||||||
|
private readonly bitrate: number
|
||||||
|
private readonly ratio: number
|
||||||
|
|
||||||
private readonly videoId: number
|
private readonly videoId: number
|
||||||
private readonly videoUUID: string
|
private readonly videoUUID: string
|
||||||
private readonly saveReplay: boolean
|
private readonly saveReplay: boolean
|
||||||
|
@ -85,6 +87,7 @@ class MuxingSession extends EventEmitter {
|
||||||
rtmpUrl: string
|
rtmpUrl: string
|
||||||
fps: number
|
fps: number
|
||||||
bitrate: number
|
bitrate: number
|
||||||
|
ratio: number
|
||||||
allResolutions: number[]
|
allResolutions: number[]
|
||||||
}) {
|
}) {
|
||||||
super()
|
super()
|
||||||
|
@ -96,7 +99,10 @@ class MuxingSession extends EventEmitter {
|
||||||
this.streamingPlaylist = options.streamingPlaylist
|
this.streamingPlaylist = options.streamingPlaylist
|
||||||
this.rtmpUrl = options.rtmpUrl
|
this.rtmpUrl = options.rtmpUrl
|
||||||
this.fps = options.fps
|
this.fps = options.fps
|
||||||
|
|
||||||
this.bitrate = options.bitrate
|
this.bitrate = options.bitrate
|
||||||
|
this.ratio = options.bitrate
|
||||||
|
|
||||||
this.allResolutions = options.allResolutions
|
this.allResolutions = options.allResolutions
|
||||||
|
|
||||||
this.videoId = this.videoLive.Video.id
|
this.videoId = this.videoLive.Video.id
|
||||||
|
@ -122,6 +128,7 @@ class MuxingSession extends EventEmitter {
|
||||||
resolutions: this.allResolutions,
|
resolutions: this.allResolutions,
|
||||||
fps: this.fps,
|
fps: this.fps,
|
||||||
bitrate: this.bitrate,
|
bitrate: this.bitrate,
|
||||||
|
ratio: this.ratio,
|
||||||
|
|
||||||
availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
|
availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
|
||||||
profile: CONFIG.LIVE.TRANSCODING.PROFILE
|
profile: CONFIG.LIVE.TRANSCODING.PROFILE
|
||||||
|
|
|
@ -1,23 +1,24 @@
|
||||||
import { logger } from '@server/helpers/logger'
|
import { logger } from '@server/helpers/logger'
|
||||||
import { AvailableEncoders, EncoderOptionsBuilder, getTargetBitrate, VideoResolution } from '../../../shared/models/videos'
|
import { getAverageBitrate } from '@shared/core-utils'
|
||||||
|
import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams } from '../../../shared/models/videos'
|
||||||
import { buildStreamSuffix, resetSupportedEncoders } from '../../helpers/ffmpeg-utils'
|
import { buildStreamSuffix, resetSupportedEncoders } from '../../helpers/ffmpeg-utils'
|
||||||
import { canDoQuickAudioTranscode, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '../../helpers/ffprobe-utils'
|
import { canDoQuickAudioTranscode, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '../../helpers/ffprobe-utils'
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Available encoders and profiles for the transcoding jobs
|
* Available encoders and profiles for the transcoding jobs
|
||||||
* These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
|
* These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
|
||||||
*
|
*
|
||||||
|
* Resources:
|
||||||
|
* * https://slhck.info/video/2017/03/01/rate-control.html
|
||||||
|
* * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Resources:
|
const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async (options: EncoderOptionsBuilderParams) => {
|
||||||
// * https://slhck.info/video/2017/03/01/rate-control.html
|
const { fps, inputRatio, inputBitrate } = options
|
||||||
// * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
|
if (!fps) return { outputOptions: [ ] }
|
||||||
|
|
||||||
const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ inputBitrate, resolution, fps }) => {
|
const targetBitrate = capBitrate(inputBitrate, getAverageBitrate({ ...options, fps, ratio: inputRatio }))
|
||||||
const targetBitrate = buildTargetBitrate({ inputBitrate, resolution, fps })
|
|
||||||
if (!targetBitrate) return { outputOptions: [ ] }
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
outputOptions: [
|
outputOptions: [
|
||||||
|
@ -29,8 +30,10 @@ const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ inputBitrat
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, inputBitrate, streamNum }) => {
|
const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async (options: EncoderOptionsBuilderParams) => {
|
||||||
const targetBitrate = buildTargetBitrate({ inputBitrate, resolution, fps })
|
const { streamNum, fps, inputBitrate, inputRatio } = options
|
||||||
|
|
||||||
|
const targetBitrate = capBitrate(inputBitrate, getAverageBitrate({ ...options, fps, ratio: inputRatio }))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
outputOptions: [
|
outputOptions: [
|
||||||
|
@ -231,14 +234,7 @@ export {
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function buildTargetBitrate (options: {
|
function capBitrate (inputBitrate: number, targetBitrate: number) {
|
||||||
inputBitrate: number
|
|
||||||
resolution: VideoResolution
|
|
||||||
fps: number
|
|
||||||
}) {
|
|
||||||
const { inputBitrate, resolution, fps } = options
|
|
||||||
|
|
||||||
const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
|
|
||||||
if (!inputBitrate) return targetBitrate
|
if (!inputBitrate) return targetBitrate
|
||||||
|
|
||||||
return Math.min(targetBitrate, inputBitrate)
|
return Math.min(targetBitrate, inputBitrate)
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
import 'mocha'
|
import 'mocha'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import { basename, join } from 'path'
|
import { basename, join } from 'path'
|
||||||
import { ffprobePromise, getVideoFileBitrate, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils'
|
import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils'
|
||||||
import {
|
import {
|
||||||
checkLiveCleanupAfterSave,
|
checkLiveCleanupAfterSave,
|
||||||
checkLiveSegmentHash,
|
checkLiveSegmentHash,
|
||||||
|
|
|
@ -3,6 +3,7 @@
|
||||||
import 'mocha'
|
import 'mocha'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import { omit } from 'lodash'
|
import { omit } from 'lodash'
|
||||||
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
import {
|
import {
|
||||||
buildAbsoluteFixturePath,
|
buildAbsoluteFixturePath,
|
||||||
cleanupTests,
|
cleanupTests,
|
||||||
|
@ -17,8 +18,7 @@ import {
|
||||||
waitJobs,
|
waitJobs,
|
||||||
webtorrentAdd
|
webtorrentAdd
|
||||||
} from '@shared/extra-utils'
|
} from '@shared/extra-utils'
|
||||||
import { getMaxBitrate, HttpStatusCode, VideoResolution, VideoState } from '@shared/models'
|
import { HttpStatusCode, VideoState } from '@shared/models'
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants'
|
|
||||||
import {
|
import {
|
||||||
canDoQuickTranscode,
|
canDoQuickTranscode,
|
||||||
getAudioStream,
|
getAudioStream,
|
||||||
|
@ -191,15 +191,6 @@ describe('Test video transcoding', function () {
|
||||||
it('Should accept and transcode additional extensions', async function () {
|
it('Should accept and transcode additional extensions', async function () {
|
||||||
this.timeout(300_000)
|
this.timeout(300_000)
|
||||||
|
|
||||||
let tempFixturePath: string
|
|
||||||
|
|
||||||
{
|
|
||||||
tempFixturePath = await generateHighBitrateVideo()
|
|
||||||
|
|
||||||
const bitrate = await getVideoFileBitrate(tempFixturePath)
|
|
||||||
expect(bitrate).to.be.above(getMaxBitrate(VideoResolution.H_1080P, 25, VIDEO_TRANSCODING_FPS))
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const fixture of [ 'video_short.mkv', 'video_short.avi' ]) {
|
for (const fixture of [ 'video_short.mkv', 'video_short.avi' ]) {
|
||||||
const attributes = {
|
const attributes = {
|
||||||
name: fixture,
|
name: fixture,
|
||||||
|
@ -555,14 +546,7 @@ describe('Test video transcoding', function () {
|
||||||
it('Should respect maximum bitrate values', async function () {
|
it('Should respect maximum bitrate values', async function () {
|
||||||
this.timeout(160_000)
|
this.timeout(160_000)
|
||||||
|
|
||||||
let tempFixturePath: string
|
const tempFixturePath = await generateHighBitrateVideo()
|
||||||
|
|
||||||
{
|
|
||||||
tempFixturePath = await generateHighBitrateVideo()
|
|
||||||
|
|
||||||
const bitrate = await getVideoFileBitrate(tempFixturePath)
|
|
||||||
expect(bitrate).to.be.above(getMaxBitrate(VideoResolution.H_1080P, 25, VIDEO_TRANSCODING_FPS))
|
|
||||||
}
|
|
||||||
|
|
||||||
const attributes = {
|
const attributes = {
|
||||||
name: 'high bitrate video',
|
name: 'high bitrate video',
|
||||||
|
@ -586,10 +570,12 @@ describe('Test video transcoding', function () {
|
||||||
|
|
||||||
const bitrate = await getVideoFileBitrate(path)
|
const bitrate = await getVideoFileBitrate(path)
|
||||||
const fps = await getVideoFileFPS(path)
|
const fps = await getVideoFileFPS(path)
|
||||||
const { videoFileResolution } = await getVideoFileResolution(path)
|
const dataResolution = await getVideoFileResolution(path)
|
||||||
|
|
||||||
expect(videoFileResolution).to.equal(resolution)
|
expect(resolution).to.equal(resolution)
|
||||||
expect(bitrate).to.be.below(getMaxBitrate(videoFileResolution, fps, VIDEO_TRANSCODING_FPS))
|
|
||||||
|
const maxBitrate = getMaxBitrate({ ...dataResolution, fps })
|
||||||
|
expect(bitrate).to.be.below(maxBitrate)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
import 'mocha'
|
import 'mocha'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
import {
|
import {
|
||||||
cleanupTests,
|
cleanupTests,
|
||||||
createMultipleServers,
|
createMultipleServers,
|
||||||
|
@ -12,9 +13,7 @@ import {
|
||||||
wait,
|
wait,
|
||||||
waitJobs
|
waitJobs
|
||||||
} from '@shared/extra-utils'
|
} from '@shared/extra-utils'
|
||||||
import { getMaxBitrate, VideoResolution } from '@shared/models'
|
|
||||||
import { getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../../helpers/ffprobe-utils'
|
import { getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../../helpers/ffprobe-utils'
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
|
|
||||||
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
|
|
||||||
|
@ -30,14 +29,7 @@ describe('Test optimize old videos', function () {
|
||||||
|
|
||||||
await doubleFollow(servers[0], servers[1])
|
await doubleFollow(servers[0], servers[1])
|
||||||
|
|
||||||
let tempFixturePath: string
|
const tempFixturePath = await generateHighBitrateVideo()
|
||||||
|
|
||||||
{
|
|
||||||
tempFixturePath = await generateHighBitrateVideo()
|
|
||||||
|
|
||||||
const bitrate = await getVideoFileBitrate(tempFixturePath)
|
|
||||||
expect(bitrate).to.be.above(getMaxBitrate(VideoResolution.H_1080P, 25, VIDEO_TRANSCODING_FPS))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload two videos for our needs
|
// Upload two videos for our needs
|
||||||
await servers[0].videos.upload({ attributes: { name: 'video1', fixture: tempFixturePath } })
|
await servers[0].videos.upload({ attributes: { name: 'video1', fixture: tempFixturePath } })
|
||||||
|
@ -88,10 +80,12 @@ describe('Test optimize old videos', function () {
|
||||||
const path = servers[0].servers.buildWebTorrentFilePath(file.fileUrl)
|
const path = servers[0].servers.buildWebTorrentFilePath(file.fileUrl)
|
||||||
const bitrate = await getVideoFileBitrate(path)
|
const bitrate = await getVideoFileBitrate(path)
|
||||||
const fps = await getVideoFileFPS(path)
|
const fps = await getVideoFileFPS(path)
|
||||||
const resolution = await getVideoFileResolution(path)
|
const data = await getVideoFileResolution(path)
|
||||||
|
|
||||||
expect(resolution.videoFileResolution).to.equal(file.resolution.id)
|
expect(data.resolution).to.equal(file.resolution.id)
|
||||||
expect(bitrate).to.be.below(getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS))
|
|
||||||
|
const maxBitrate = getMaxBitrate({ ...data, fps })
|
||||||
|
expect(bitrate).to.be.below(maxBitrate)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
@ -3,16 +3,16 @@
|
||||||
import 'mocha'
|
import 'mocha'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import { getVideoFileBitrate, getVideoFileFPS } from '@server/helpers/ffprobe-utils'
|
import { getVideoFileBitrate, getVideoFileFPS } from '@server/helpers/ffprobe-utils'
|
||||||
import { CLICommand } from '@shared/extra-utils'
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
import { getTargetBitrate, VideoResolution } from '../../../shared/models/videos'
|
import { buildAbsoluteFixturePath, CLICommand } from '@shared/extra-utils'
|
||||||
import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
|
import { VideoResolution } from '../../../shared/models/videos'
|
||||||
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
|
|
||||||
describe('Test create transcoding jobs', function () {
|
describe('Test create transcoding jobs', function () {
|
||||||
|
|
||||||
it('Should print the correct command for each resolution', async function () {
|
it('Should print the correct command for each resolution', async function () {
|
||||||
const fixturePath = 'server/tests/fixtures/video_short.webm'
|
const fixturePath = buildAbsoluteFixturePath('video_short.webm')
|
||||||
const fps = await getVideoFileFPS(fixturePath)
|
const fps = await getVideoFileFPS(fixturePath)
|
||||||
const bitrate = await getVideoFileBitrate(fixturePath)
|
const bitrate = await getVideoFileBitrate(fixturePath)
|
||||||
|
|
||||||
|
@ -21,7 +21,7 @@ describe('Test create transcoding jobs', function () {
|
||||||
VideoResolution.H_1080P
|
VideoResolution.H_1080P
|
||||||
]) {
|
]) {
|
||||||
const command = await CLICommand.exec(`npm run print-transcode-command -- ${fixturePath} -r ${resolution}`)
|
const command = await CLICommand.exec(`npm run print-transcode-command -- ${fixturePath} -r ${resolution}`)
|
||||||
const targetBitrate = Math.min(getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS), bitrate)
|
const targetBitrate = Math.min(getMaxBitrate({ resolution, fps, ratio: 16 / 9 }), bitrate)
|
||||||
|
|
||||||
expect(command).to.includes(`-vf scale=w=-2:h=${resolution}`)
|
expect(command).to.includes(`-vf scale=w=-2:h=${resolution}`)
|
||||||
expect(command).to.includes(`-y -acodec aac -vcodec libx264`)
|
expect(command).to.includes(`-y -acodec aac -vcodec libx264`)
|
||||||
|
|
|
@ -4,6 +4,8 @@ import 'mocha'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import { snakeCase } from 'lodash'
|
import { snakeCase } from 'lodash'
|
||||||
import validator from 'validator'
|
import validator from 'validator'
|
||||||
|
import { getAverageBitrate, getMaxBitrate } from '@shared/core-utils'
|
||||||
|
import { VideoResolution } from '@shared/models'
|
||||||
import { objectConverter, parseBytes } from '../../helpers/core-utils'
|
import { objectConverter, parseBytes } from '../../helpers/core-utils'
|
||||||
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
|
@ -46,6 +48,9 @@ describe('Parse Bytes', function () {
|
||||||
it('Should be invalid when given invalid value', async function () {
|
it('Should be invalid when given invalid value', async function () {
|
||||||
expect(parseBytes('6GB 1GB')).to.be.eq(6)
|
expect(parseBytes('6GB 1GB')).to.be.eq(6)
|
||||||
})
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Object', function () {
|
||||||
|
|
||||||
it('Should convert an object', async function () {
|
it('Should convert an object', async function () {
|
||||||
function keyConverter (k: string) {
|
function keyConverter (k: string) {
|
||||||
|
@ -94,3 +99,36 @@ describe('Parse Bytes', function () {
|
||||||
expect(obj['my_super_key']).to.be.undefined
|
expect(obj['my_super_key']).to.be.undefined
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('Bitrate', function () {
|
||||||
|
|
||||||
|
it('Should get appropriate max bitrate', function () {
|
||||||
|
const tests = [
|
||||||
|
{ resolution: VideoResolution.H_240P, ratio: 16 / 9, fps: 24, min: 600, max: 800 },
|
||||||
|
{ resolution: VideoResolution.H_360P, ratio: 16 / 9, fps: 24, min: 1200, max: 1600 },
|
||||||
|
{ resolution: VideoResolution.H_480P, ratio: 16 / 9, fps: 24, min: 2000, max: 2300 },
|
||||||
|
{ resolution: VideoResolution.H_720P, ratio: 16 / 9, fps: 24, min: 4000, max: 4400 },
|
||||||
|
{ resolution: VideoResolution.H_1080P, ratio: 16 / 9, fps: 24, min: 8000, max: 10000 },
|
||||||
|
{ resolution: VideoResolution.H_4K, ratio: 16 / 9, fps: 24, min: 25000, max: 30000 }
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const test of tests) {
|
||||||
|
expect(getMaxBitrate(test)).to.be.above(test.min * 1000).and.below(test.max * 1000)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Should get appropriate average bitrate', function () {
|
||||||
|
const tests = [
|
||||||
|
{ resolution: VideoResolution.H_240P, ratio: 16 / 9, fps: 24, min: 350, max: 450 },
|
||||||
|
{ resolution: VideoResolution.H_360P, ratio: 16 / 9, fps: 24, min: 700, max: 900 },
|
||||||
|
{ resolution: VideoResolution.H_480P, ratio: 16 / 9, fps: 24, min: 1100, max: 1300 },
|
||||||
|
{ resolution: VideoResolution.H_720P, ratio: 16 / 9, fps: 24, min: 2300, max: 2500 },
|
||||||
|
{ resolution: VideoResolution.H_1080P, ratio: 16 / 9, fps: 24, min: 4700, max: 5000 },
|
||||||
|
{ resolution: VideoResolution.H_4K, ratio: 16 / 9, fps: 24, min: 15000, max: 17000 }
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const test of tests) {
|
||||||
|
expect(getAverageBitrate(test)).to.be.above(test.min * 1000).and.below(test.max * 1000)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
@ -5,3 +5,4 @@ export * from './plugins'
|
||||||
export * from './renderer'
|
export * from './renderer'
|
||||||
export * from './users'
|
export * from './users'
|
||||||
export * from './utils'
|
export * from './utils'
|
||||||
|
export * from './videos'
|
||||||
|
|
|
@ -0,0 +1,86 @@
|
||||||
|
import { VideoResolution } from "@shared/models"
|
||||||
|
|
||||||
|
type BitPerPixel = { [ id in VideoResolution ]: number }
|
||||||
|
|
||||||
|
// https://bitmovin.com/video-bitrate-streaming-hls-dash/
|
||||||
|
|
||||||
|
const averageBitPerPixel: BitPerPixel = {
|
||||||
|
[VideoResolution.H_NOVIDEO]: 0,
|
||||||
|
[VideoResolution.H_240P]: 0.17,
|
||||||
|
[VideoResolution.H_360P]: 0.15,
|
||||||
|
[VideoResolution.H_480P]: 0.12,
|
||||||
|
[VideoResolution.H_720P]: 0.11,
|
||||||
|
[VideoResolution.H_1080P]: 0.10,
|
||||||
|
[VideoResolution.H_1440P]: 0.09,
|
||||||
|
[VideoResolution.H_4K]: 0.08
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxBitPerPixel: BitPerPixel = {
|
||||||
|
[VideoResolution.H_NOVIDEO]: 0,
|
||||||
|
[VideoResolution.H_240P]: 0.29,
|
||||||
|
[VideoResolution.H_360P]: 0.26,
|
||||||
|
[VideoResolution.H_480P]: 0.22,
|
||||||
|
[VideoResolution.H_720P]: 0.19,
|
||||||
|
[VideoResolution.H_1080P]: 0.17,
|
||||||
|
[VideoResolution.H_1440P]: 0.16,
|
||||||
|
[VideoResolution.H_4K]: 0.14
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAverageBitrate (options: {
|
||||||
|
resolution: VideoResolution
|
||||||
|
ratio: number
|
||||||
|
fps: number
|
||||||
|
}) {
|
||||||
|
const targetBitrate = calculateBitrate({ ...options, bitPerPixel: averageBitPerPixel })
|
||||||
|
if (!targetBitrate) return 192 * 1000
|
||||||
|
|
||||||
|
return targetBitrate
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMaxBitrate (options: {
|
||||||
|
resolution: VideoResolution
|
||||||
|
ratio: number
|
||||||
|
fps: number
|
||||||
|
}) {
|
||||||
|
const targetBitrate = calculateBitrate({ ...options, bitPerPixel: maxBitPerPixel })
|
||||||
|
if (!targetBitrate) return 256 * 1000
|
||||||
|
|
||||||
|
return targetBitrate
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export {
|
||||||
|
getAverageBitrate,
|
||||||
|
getMaxBitrate
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function calculateBitrate (options: {
|
||||||
|
bitPerPixel: BitPerPixel
|
||||||
|
resolution: VideoResolution
|
||||||
|
ratio: number
|
||||||
|
fps: number
|
||||||
|
}) {
|
||||||
|
const { bitPerPixel, resolution, ratio, fps } = options
|
||||||
|
|
||||||
|
const resolutionsOrder = [
|
||||||
|
VideoResolution.H_4K,
|
||||||
|
VideoResolution.H_1440P,
|
||||||
|
VideoResolution.H_1080P,
|
||||||
|
VideoResolution.H_720P,
|
||||||
|
VideoResolution.H_480P,
|
||||||
|
VideoResolution.H_360P,
|
||||||
|
VideoResolution.H_240P,
|
||||||
|
VideoResolution.H_NOVIDEO
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const toTestResolution of resolutionsOrder) {
|
||||||
|
if (toTestResolution <= resolution) {
|
||||||
|
return resolution * resolution * ratio * fps * bitPerPixel[toTestResolution]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Unknown resolution ' + resolution)
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
export * from './bitrate'
|
|
@ -1,8 +1,20 @@
|
||||||
|
import { expect } from 'chai'
|
||||||
import * as ffmpeg from 'fluent-ffmpeg'
|
import * as ffmpeg from 'fluent-ffmpeg'
|
||||||
import { ensureDir, pathExists } from 'fs-extra'
|
import { ensureDir, pathExists } from 'fs-extra'
|
||||||
import { dirname } from 'path'
|
import { dirname } from 'path'
|
||||||
|
import { getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
|
||||||
|
import { getMaxBitrate } from '@shared/core-utils'
|
||||||
import { buildAbsoluteFixturePath } from './tests'
|
import { buildAbsoluteFixturePath } from './tests'
|
||||||
|
|
||||||
|
async function ensureHasTooBigBitrate (fixturePath: string) {
|
||||||
|
const bitrate = await getVideoFileBitrate(fixturePath)
|
||||||
|
const dataResolution = await getVideoFileResolution(fixturePath)
|
||||||
|
const fps = await getVideoFileFPS(fixturePath)
|
||||||
|
|
||||||
|
const maxBitrate = getMaxBitrate({ ...dataResolution, fps })
|
||||||
|
expect(bitrate).to.be.above(maxBitrate)
|
||||||
|
}
|
||||||
|
|
||||||
async function generateHighBitrateVideo () {
|
async function generateHighBitrateVideo () {
|
||||||
const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true)
|
const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true)
|
||||||
|
|
||||||
|
@ -28,6 +40,8 @@ async function generateHighBitrateVideo () {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await ensureHasTooBigBitrate(tempFixturePath)
|
||||||
|
|
||||||
return tempFixturePath
|
return tempFixturePath
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
import { VideoTranscodingFPS } from './video-transcoding-fps.model'
|
|
||||||
|
|
||||||
export const enum VideoResolution {
|
export const enum VideoResolution {
|
||||||
H_NOVIDEO = 0,
|
H_NOVIDEO = 0,
|
||||||
H_240P = 240,
|
H_240P = 240,
|
||||||
|
@ -10,90 +8,3 @@ export const enum VideoResolution {
|
||||||
H_1440P = 1440,
|
H_1440P = 1440,
|
||||||
H_4K = 2160
|
H_4K = 2160
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Bitrate targets for different resolutions, at VideoTranscodingFPS.AVERAGE.
|
|
||||||
*
|
|
||||||
* Sources for individual quality levels:
|
|
||||||
* Google Live Encoder: https://support.google.com/youtube/answer/2853702?hl=en
|
|
||||||
* YouTube Video Info: youtube-dl --list-formats, with sample videos
|
|
||||||
*/
|
|
||||||
function getBaseBitrate (resolution: number) {
|
|
||||||
if (resolution === VideoResolution.H_NOVIDEO) {
|
|
||||||
// audio-only
|
|
||||||
return 64 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_240P) {
|
|
||||||
// quality according to Google Live Encoder: 300 - 700 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 285 Kbps
|
|
||||||
return 320 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_360P) {
|
|
||||||
// quality according to Google Live Encoder: 400 - 1,000 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 700 Kbps
|
|
||||||
return 780 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_480P) {
|
|
||||||
// quality according to Google Live Encoder: 500 - 2,000 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 1300 Kbps
|
|
||||||
return 1500 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_720P) {
|
|
||||||
// quality according to Google Live Encoder: 1,500 - 4,000 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 2680 Kbps
|
|
||||||
return 2800 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_1080P) {
|
|
||||||
// quality according to Google Live Encoder: 3000 - 6000 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 5081 Kbps
|
|
||||||
return 5200 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resolution <= VideoResolution.H_1440P) {
|
|
||||||
// quality according to Google Live Encoder: 6000 - 13000 Kbps
|
|
||||||
// Quality according to YouTube Video Info: 8600 (av01) - 17000 (vp9.2) Kbps
|
|
||||||
return 10_000 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4K
|
|
||||||
// quality according to Google Live Encoder: 13000 - 34000 Kbps
|
|
||||||
return 22_000 * 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculate the target bitrate based on video resolution and FPS.
|
|
||||||
*
|
|
||||||
* The calculation is based on two values:
|
|
||||||
* Bitrate at VideoTranscodingFPS.AVERAGE is always the same as
|
|
||||||
* getBaseBitrate(). Bitrate at VideoTranscodingFPS.MAX is always
|
|
||||||
* getBaseBitrate() * 1.4. All other values are calculated linearly
|
|
||||||
* between these two points.
|
|
||||||
*/
|
|
||||||
export function getTargetBitrate (resolution: number, fps: number, fpsTranscodingConstants: VideoTranscodingFPS) {
|
|
||||||
const baseBitrate = getBaseBitrate(resolution)
|
|
||||||
// The maximum bitrate, used when fps === VideoTranscodingFPS.MAX
|
|
||||||
// Based on numbers from Youtube, 60 fps bitrate divided by 30 fps bitrate:
|
|
||||||
// 720p: 2600 / 1750 = 1.49
|
|
||||||
// 1080p: 4400 / 3300 = 1.33
|
|
||||||
const maxBitrate = baseBitrate * 1.4
|
|
||||||
const maxBitrateDifference = maxBitrate - baseBitrate
|
|
||||||
const maxFpsDifference = fpsTranscodingConstants.MAX - fpsTranscodingConstants.AVERAGE
|
|
||||||
// For 1080p video with default settings, this results in the following formula:
|
|
||||||
// 3300 + (x - 30) * (1320/30)
|
|
||||||
// Example outputs:
|
|
||||||
// 1080p10: 2420 kbps, 1080p30: 3300 kbps, 1080p60: 4620 kbps
|
|
||||||
// 720p10: 1283 kbps, 720p30: 1750 kbps, 720p60: 2450 kbps
|
|
||||||
return Math.floor(baseBitrate + (fps - fpsTranscodingConstants.AVERAGE) * (maxBitrateDifference / maxFpsDifference))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The maximum bitrate we expect to see on a transcoded video in bytes per second.
|
|
||||||
*/
|
|
||||||
export function getMaxBitrate (resolution: VideoResolution, fps: number, fpsTranscodingConstants: VideoTranscodingFPS) {
|
|
||||||
return getTargetBitrate(resolution, fps, fpsTranscodingConstants) * 2
|
|
||||||
}
|
|
||||||
|
|
|
@ -2,13 +2,23 @@ import { VideoResolution } from './video-resolution.enum'
|
||||||
|
|
||||||
// Types used by plugins and ffmpeg-utils
|
// Types used by plugins and ffmpeg-utils
|
||||||
|
|
||||||
export type EncoderOptionsBuilder = (params: {
|
export type EncoderOptionsBuilderParams = {
|
||||||
input: string
|
input: string
|
||||||
|
|
||||||
resolution: VideoResolution
|
resolution: VideoResolution
|
||||||
inputBitrate: number
|
|
||||||
|
// Could be null for "merge audio" transcoding
|
||||||
fps?: number
|
fps?: number
|
||||||
|
|
||||||
|
// Could be undefined if we could not get input bitrate (some RTMP streams for example)
|
||||||
|
inputBitrate: number
|
||||||
|
inputRatio: number
|
||||||
|
|
||||||
|
// For lives
|
||||||
streamNum?: number
|
streamNum?: number
|
||||||
}) => Promise<EncoderOptions> | EncoderOptions
|
}
|
||||||
|
|
||||||
|
export type EncoderOptionsBuilder = (params: EncoderOptionsBuilderParams) => Promise<EncoderOptions> | EncoderOptions
|
||||||
|
|
||||||
export interface EncoderOptions {
|
export interface EncoderOptions {
|
||||||
copy?: boolean // Copy stream? Default to false
|
copy?: boolean // Copy stream? Default to false
|
||||||
|
|
Loading…
Reference in New Issue