1 import { FfprobeData } from 'fluent-ffmpeg'
2 import { getMaxBitrate } from '@shared/core-utils'
10 getVideoStreamDimensionsInfo,
11 getVideoStreamDuration,
14 } from '@shared/extra-utils/ffprobe'
15 import { VideoResolution, VideoTranscodingFPS } from '@shared/models'
16 import { CONFIG } from '../../initializers/config'
17 import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
18 import { logger } from '../logger'
22 * Helpers to run ffprobe and extract data from the JSON output
26 // ---------------------------------------------------------------------------
28 // ---------------------------------------------------------------------------
30 async function getVideoStreamCodec (path: string) {
31 const videoStream = await getVideoStream(path)
32 if (!videoStream) return ''
34 const videoCodec = videoStream.codec_tag_string
36 if (videoCodec === 'vp09') return 'vp09.00.50.08'
37 if (videoCodec === 'hev1') return 'hev1.1.6.L93.B0'
39 const baseProfileMatrix = {
52 let baseProfile = baseProfileMatrix[videoCodec][videoStream.profile]
54 logger.warn('Cannot get video profile codec of %s.', path, { videoStream })
55 baseProfile = baseProfileMatrix[videoCodec]['High'] // Fallback
58 let level = videoStream.level.toString(16)
59 if (level.length === 1) level = `0${level}`
61 if (videoCodec === 'av01') {
62 // Guess the tier indicator and bit depth
63 return `${videoCodec}.${baseProfile}.${level}M.08`
66 // Default, h264 codec
67 return `${videoCodec}.${baseProfile}${level}`
70 async function getAudioStreamCodec (path: string, existingProbe?: FfprobeData) {
71 const { audioStream } = await getAudioStream(path, existingProbe)
73 if (!audioStream) return ''
75 const audioCodecName = audioStream.codec_name
77 if (audioCodecName === 'opus') return 'opus'
78 if (audioCodecName === 'vorbis') return 'vorbis'
79 if (audioCodecName === 'aac') return 'mp4a.40.2'
80 if (audioCodecName === 'mp3') return 'mp4a.40.34'
82 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
84 return 'mp4a.40.2' // Fallback
87 // ---------------------------------------------------------------------------
89 // ---------------------------------------------------------------------------
91 function computeResolutionsToTranscode (options: {
97 const { input, type, includeInput, strictLower } = options
99 const configResolutions = type === 'vod'
100 ? CONFIG.TRANSCODING.RESOLUTIONS
101 : CONFIG.LIVE.TRANSCODING.RESOLUTIONS
103 const resolutionsEnabled = new Set<number>()
105 // Put in the order we want to proceed jobs
106 const availableResolutions: VideoResolution[] = [
107 VideoResolution.H_NOVIDEO,
108 VideoResolution.H_480P,
109 VideoResolution.H_360P,
110 VideoResolution.H_720P,
111 VideoResolution.H_240P,
112 VideoResolution.H_144P,
113 VideoResolution.H_1080P,
114 VideoResolution.H_1440P,
118 for (const resolution of availableResolutions) {
119 // Resolution not enabled
120 if (configResolutions[resolution + 'p'] !== true) continue
121 // Too big resolution for input file
122 if (input < resolution) continue
123 // We only want lower resolutions than input file
124 if (strictLower && input === resolution) continue
126 resolutionsEnabled.add(resolution)
130 resolutionsEnabled.add(input)
133 return Array.from(resolutionsEnabled)
136 // ---------------------------------------------------------------------------
137 // Can quick transcode
138 // ---------------------------------------------------------------------------
140 async function canDoQuickTranscode (path: string): Promise<boolean> {
141 if (CONFIG.TRANSCODING.PROFILE !== 'default') return false
143 const probe = await ffprobePromise(path)
145 return await canDoQuickVideoTranscode(path, probe) &&
146 await canDoQuickAudioTranscode(path, probe)
149 async function canDoQuickAudioTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
150 const parsedAudio = await getAudioStream(path, probe)
152 if (!parsedAudio.audioStream) return true
154 if (parsedAudio.audioStream['codec_name'] !== 'aac') return false
156 const audioBitrate = parsedAudio.bitrate
157 if (!audioBitrate) return false
159 const maxAudioBitrate = getMaxAudioBitrate('aac', audioBitrate)
160 if (maxAudioBitrate !== -1 && audioBitrate > maxAudioBitrate) return false
162 const channelLayout = parsedAudio.audioStream['channel_layout']
163 // Causes playback issues with Chrome
164 if (!channelLayout || channelLayout === 'unknown' || channelLayout === 'quad') return false
169 async function canDoQuickVideoTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
170 const videoStream = await getVideoStream(path, probe)
171 const fps = await getVideoStreamFPS(path, probe)
172 const bitRate = await getVideoStreamBitrate(path, probe)
173 const resolutionData = await getVideoStreamDimensionsInfo(path, probe)
175 // If ffprobe did not manage to guess the bitrate
176 if (!bitRate) return false
178 // check video params
179 if (!videoStream) return false
180 if (videoStream['codec_name'] !== 'h264') return false
181 if (videoStream['pix_fmt'] !== 'yuv420p') return false
182 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
183 if (bitRate > getMaxBitrate({ ...resolutionData, fps })) return false
188 // ---------------------------------------------------------------------------
190 // ---------------------------------------------------------------------------
192 function getClosestFramerateStandard <K extends keyof Pick<VideoTranscodingFPS, 'HD_STANDARD' | 'STANDARD'>> (fps: number, type: K) {
193 return VIDEO_TRANSCODING_FPS[type].slice(0)
194 .sort((a, b) => fps % a - fps % b)[0]
197 function computeFPS (fpsArg: number, resolution: VideoResolution) {
201 // On small/medium resolutions, limit FPS
202 resolution !== undefined &&
203 resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
204 fps > VIDEO_TRANSCODING_FPS.AVERAGE
206 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
207 fps = getClosestFramerateStandard(fps, 'STANDARD')
211 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
213 if (fps < VIDEO_TRANSCODING_FPS.MIN) {
214 throw new Error(`Cannot compute FPS because ${fps} is lower than our minimum value ${VIDEO_TRANSCODING_FPS.MIN}`)
220 // ---------------------------------------------------------------------------
223 // Re export ffprobe utils
224 getVideoStreamDimensionsInfo,
228 getVideoStreamDuration,
233 getVideoStreamBitrate,
239 getClosestFramerateStandard,
241 computeResolutionsToTranscode,
244 canDoQuickVideoTranscode,
245 canDoQuickAudioTranscode