1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { VideoFileMetadata } from '@shared/models/videos/video-file-metadata'
3 import { getMaxBitrate, VideoResolution } from '../../shared/models/videos'
4 import { CONFIG } from '../initializers/config'
5 import { VIDEO_TRANSCODING_FPS } from '../initializers/constants'
6 import { logger } from './logger'
8 function ffprobePromise (path: string) {
9 return new Promise<ffmpeg.FfprobeData>((res, rej) => {
10 ffmpeg.ffprobe(path, (err, data) => {
11 if (err) return rej(err)
18 async function getAudioStream (videoPath: string, existingProbe?: ffmpeg.FfprobeData) {
19 // without position, ffprobe considers the last input only
20 // we make it consider the first input only
21 // if you pass a file path to pos, then ffprobe acts on that file directly
22 const data = existingProbe || await ffprobePromise(videoPath)
24 if (Array.isArray(data.streams)) {
25 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
29 absolutePath: data.format.filename,
31 bitrate: parseInt(audioStream['bit_rate'] + '', 10)
36 return { absolutePath: data.format.filename }
39 function getMaxAudioBitrate (type: 'aac' | 'mp3' | string, bitrate: number) {
40 const baseKbitrate = 384
41 const toBits = (kbits: number) => kbits * 8000
45 case bitrate > toBits(baseKbitrate):
49 return -1 // we interpret it as a signal to copy the audio stream as is
55 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
56 That's why, when using aac, we can go to lower kbit/sec. The equivalences
57 made here are not made to be accurate, especially with good mp3 encoders.
60 case bitrate <= toBits(192):
63 case bitrate <= toBits(384):
74 async function getVideoStreamSize (path: string, existingProbe?: ffmpeg.FfprobeData) {
75 const videoStream = await getVideoStreamFromFile(path, existingProbe)
77 return videoStream === null
78 ? { width: 0, height: 0 }
79 : { width: videoStream.width, height: videoStream.height }
82 async function getVideoStreamCodec (path: string) {
83 const videoStream = await getVideoStreamFromFile(path)
85 if (!videoStream) return ''
87 const videoCodec = videoStream.codec_tag_string
89 const baseProfileMatrix = {
95 let baseProfile = baseProfileMatrix[videoStream.profile]
97 logger.warn('Cannot get video profile codec of %s.', path, { videoStream })
98 baseProfile = baseProfileMatrix['High'] // Fallback
101 let level = videoStream.level.toString(16)
102 if (level.length === 1) level = `0${level}`
104 return `${videoCodec}.${baseProfile}${level}`
107 async function getAudioStreamCodec (path: string, existingProbe?: ffmpeg.FfprobeData) {
108 const { audioStream } = await getAudioStream(path, existingProbe)
110 if (!audioStream) return ''
112 const audioCodec = audioStream.codec_name
113 if (audioCodec === 'aac') return 'mp4a.40.2'
115 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
117 return 'mp4a.40.2' // Fallback
120 async function getVideoFileResolution (path: string, existingProbe?: ffmpeg.FfprobeData) {
121 const size = await getVideoStreamSize(path, existingProbe)
124 videoFileResolution: Math.min(size.height, size.width),
125 isPortraitMode: size.height > size.width
129 async function getVideoFileFPS (path: string, existingProbe?: ffmpeg.FfprobeData) {
130 const videoStream = await getVideoStreamFromFile(path, existingProbe)
131 if (videoStream === null) return 0
133 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
134 const valuesText: string = videoStream[key]
135 if (!valuesText) continue
137 const [ frames, seconds ] = valuesText.split('/')
138 if (!frames || !seconds) continue
140 const result = parseInt(frames, 10) / parseInt(seconds, 10)
141 if (result > 0) return Math.round(result)
147 async function getMetadataFromFile (path: string, existingProbe?: ffmpeg.FfprobeData) {
148 const metadata = existingProbe || await ffprobePromise(path)
150 return new VideoFileMetadata(metadata)
153 async function getVideoFileBitrate (path: string, existingProbe?: ffmpeg.FfprobeData) {
154 const metadata = await getMetadataFromFile(path, existingProbe)
156 return metadata.format.bit_rate as number
159 async function getDurationFromVideoFile (path: string, existingProbe?: ffmpeg.FfprobeData) {
160 const metadata = await getMetadataFromFile(path, existingProbe)
162 return Math.floor(metadata.format.duration)
165 async function getVideoStreamFromFile (path: string, existingProbe?: ffmpeg.FfprobeData) {
166 const metadata = await getMetadataFromFile(path, existingProbe)
168 return metadata.streams.find(s => s.codec_type === 'video') || null
171 function computeResolutionsToTranscode (videoFileResolution: number, type: 'vod' | 'live') {
172 const configResolutions = type === 'vod'
173 ? CONFIG.TRANSCODING.RESOLUTIONS
174 : CONFIG.LIVE.TRANSCODING.RESOLUTIONS
176 const resolutionsEnabled: number[] = []
178 // Put in the order we want to proceed jobs
179 const resolutions = [
180 VideoResolution.H_NOVIDEO,
181 VideoResolution.H_480P,
182 VideoResolution.H_360P,
183 VideoResolution.H_720P,
184 VideoResolution.H_240P,
185 VideoResolution.H_1080P,
189 for (const resolution of resolutions) {
190 if (configResolutions[resolution + 'p'] === true && videoFileResolution > resolution) {
191 resolutionsEnabled.push(resolution)
195 return resolutionsEnabled
198 async function canDoQuickTranscode (path: string): Promise<boolean> {
199 const probe = await ffprobePromise(path)
201 return await canDoQuickVideoTranscode(path, probe) &&
202 await canDoQuickAudioTranscode(path, probe)
205 async function canDoQuickVideoTranscode (path: string, probe?: ffmpeg.FfprobeData): Promise<boolean> {
206 const videoStream = await getVideoStreamFromFile(path, probe)
207 const fps = await getVideoFileFPS(path, probe)
208 const bitRate = await getVideoFileBitrate(path, probe)
209 const resolution = await getVideoFileResolution(path, probe)
211 // check video params
212 if (videoStream == null) return false
213 if (videoStream['codec_name'] !== 'h264') return false
214 if (videoStream['pix_fmt'] !== 'yuv420p') return false
215 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
216 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
221 async function canDoQuickAudioTranscode (path: string, probe?: ffmpeg.FfprobeData): Promise<boolean> {
222 const parsedAudio = await getAudioStream(path, probe)
224 // check audio params (if audio stream exists)
225 if (parsedAudio.audioStream) {
226 if (parsedAudio.audioStream['codec_name'] !== 'aac') return false
228 const audioBitrate = parsedAudio.bitrate
230 const maxAudioBitrate = getMaxAudioBitrate('aac', audioBitrate)
231 if (maxAudioBitrate !== -1 && audioBitrate > maxAudioBitrate) return false
237 function getClosestFramerateStandard (fps: number, type: 'HD_STANDARD' | 'STANDARD'): number {
238 return VIDEO_TRANSCODING_FPS[type].slice(0)
239 .sort((a, b) => fps % a - fps % b)[0]
242 // ---------------------------------------------------------------------------
248 getVideoFileResolution,
251 getVideoStreamFromFile,
252 getDurationFromVideoFile,
256 getClosestFramerateStandard,
257 computeResolutionsToTranscode,
260 canDoQuickVideoTranscode,
261 canDoQuickAudioTranscode