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 { toEven } from '../core-utils'
19 import { logger } from '../logger'
23 * Helpers to run ffprobe and extract data from the JSON output
27 // ---------------------------------------------------------------------------
29 // ---------------------------------------------------------------------------
31 async function getVideoStreamCodec (path: string) {
32 const videoStream = await getVideoStream(path)
33 if (!videoStream) return ''
35 const videoCodec = videoStream.codec_tag_string
37 if (videoCodec === 'vp09') return 'vp09.00.50.08'
38 if (videoCodec === 'hev1') return 'hev1.1.6.L93.B0'
40 const baseProfileMatrix = {
53 let baseProfile = baseProfileMatrix[videoCodec][videoStream.profile]
55 logger.warn('Cannot get video profile codec of %s.', path, { videoStream })
56 baseProfile = baseProfileMatrix[videoCodec]['High'] // Fallback
59 if (videoCodec === 'av01') {
60 let level = videoStream.level.toString()
61 if (level.length === 1) level = `0${level}`
63 // Guess the tier indicator and bit depth
64 return `${videoCodec}.${baseProfile}.${level}M.08`
67 let level = videoStream.level.toString(16)
68 if (level.length === 1) level = `0${level}`
70 // Default, h264 codec
71 return `${videoCodec}.${baseProfile}${level}`
74 async function getAudioStreamCodec (path: string, existingProbe?: FfprobeData) {
75 const { audioStream } = await getAudioStream(path, existingProbe)
77 if (!audioStream) return ''
79 const audioCodecName = audioStream.codec_name
81 if (audioCodecName === 'opus') return 'opus'
82 if (audioCodecName === 'vorbis') return 'vorbis'
83 if (audioCodecName === 'aac') return 'mp4a.40.2'
84 if (audioCodecName === 'mp3') return 'mp4a.40.34'
86 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
88 return 'mp4a.40.2' // Fallback
91 // ---------------------------------------------------------------------------
93 // ---------------------------------------------------------------------------
95 function computeResolutionsToTranscode (options: {
102 const { input, type, includeInput, strictLower, hasAudio } = options
104 const configResolutions = type === 'vod'
105 ? CONFIG.TRANSCODING.RESOLUTIONS
106 : CONFIG.LIVE.TRANSCODING.RESOLUTIONS
108 const resolutionsEnabled = new Set<number>()
110 // Put in the order we want to proceed jobs
111 const availableResolutions: VideoResolution[] = [
112 VideoResolution.H_NOVIDEO,
113 VideoResolution.H_480P,
114 VideoResolution.H_360P,
115 VideoResolution.H_720P,
116 VideoResolution.H_240P,
117 VideoResolution.H_144P,
118 VideoResolution.H_1080P,
119 VideoResolution.H_1440P,
123 for (const resolution of availableResolutions) {
124 // Resolution not enabled
125 if (configResolutions[resolution + 'p'] !== true) continue
126 // Too big resolution for input file
127 if (input < resolution) continue
128 // We only want lower resolutions than input file
129 if (strictLower && input === resolution) continue
130 // Audio resolutio but no audio in the video
131 if (resolution === VideoResolution.H_NOVIDEO && !hasAudio) continue
133 resolutionsEnabled.add(resolution)
137 // Always use an even resolution to avoid issues with ffmpeg
138 resolutionsEnabled.add(toEven(input))
141 return Array.from(resolutionsEnabled)
144 // ---------------------------------------------------------------------------
145 // Can quick transcode
146 // ---------------------------------------------------------------------------
148 async function canDoQuickTranscode (path: string): Promise<boolean> {
149 if (CONFIG.TRANSCODING.PROFILE !== 'default') return false
151 const probe = await ffprobePromise(path)
153 return await canDoQuickVideoTranscode(path, probe) &&
154 await canDoQuickAudioTranscode(path, probe)
157 async function canDoQuickAudioTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
158 const parsedAudio = await getAudioStream(path, probe)
160 if (!parsedAudio.audioStream) return true
162 if (parsedAudio.audioStream['codec_name'] !== 'aac') return false
164 const audioBitrate = parsedAudio.bitrate
165 if (!audioBitrate) return false
167 const maxAudioBitrate = getMaxAudioBitrate('aac', audioBitrate)
168 if (maxAudioBitrate !== -1 && audioBitrate > maxAudioBitrate) return false
170 const channelLayout = parsedAudio.audioStream['channel_layout']
171 // Causes playback issues with Chrome
172 if (!channelLayout || channelLayout === 'unknown' || channelLayout === 'quad') return false
177 async function canDoQuickVideoTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
178 const videoStream = await getVideoStream(path, probe)
179 const fps = await getVideoStreamFPS(path, probe)
180 const bitRate = await getVideoStreamBitrate(path, probe)
181 const resolutionData = await getVideoStreamDimensionsInfo(path, probe)
183 // If ffprobe did not manage to guess the bitrate
184 if (!bitRate) return false
186 // check video params
187 if (!videoStream) return false
188 if (videoStream['codec_name'] !== 'h264') return false
189 if (videoStream['pix_fmt'] !== 'yuv420p') return false
190 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
191 if (bitRate > getMaxBitrate({ ...resolutionData, fps })) return false
196 // ---------------------------------------------------------------------------
198 // ---------------------------------------------------------------------------
200 function getClosestFramerateStandard <K extends keyof Pick<VideoTranscodingFPS, 'HD_STANDARD' | 'STANDARD'>> (fps: number, type: K) {
201 return VIDEO_TRANSCODING_FPS[type].slice(0)
202 .sort((a, b) => fps % a - fps % b)[0]
205 function computeFPS (fpsArg: number, resolution: VideoResolution) {
209 // On small/medium resolutions, limit FPS
210 resolution !== undefined &&
211 resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
212 fps > VIDEO_TRANSCODING_FPS.AVERAGE
214 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
215 fps = getClosestFramerateStandard(fps, 'STANDARD')
219 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
221 if (fps < VIDEO_TRANSCODING_FPS.MIN) {
222 throw new Error(`Cannot compute FPS because ${fps} is lower than our minimum value ${VIDEO_TRANSCODING_FPS.MIN}`)
228 // ---------------------------------------------------------------------------
231 // Re export ffprobe utils
232 getVideoStreamDimensionsInfo,
236 getVideoStreamDuration,
241 getVideoStreamBitrate,
247 getClosestFramerateStandard,
249 computeResolutionsToTranscode,
252 canDoQuickVideoTranscode,
253 canDoQuickAudioTranscode