]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg/ffprobe-utils.ts
Use worker thread to send HTTP requests
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg / ffprobe-utils.ts
CommitLineData
06aad801 1import { FfprobeData } from 'fluent-ffmpeg'
679c12e6 2import { getMaxBitrate } from '@shared/core-utils'
06aad801 3import {
1bb4c9ab 4 buildFileMetadata,
06aad801 5 ffprobePromise,
06aad801 6 getAudioStream,
7 getMaxAudioBitrate,
c729caf6 8 getVideoStream,
1bb4c9ab 9 getVideoStreamBitrate,
c729caf6 10 getVideoStreamDimensionsInfo,
1bb4c9ab
C
11 getVideoStreamDuration,
12 getVideoStreamFPS,
c729caf6 13 hasAudioStream
06aad801 14} from '@shared/extra-utils/ffprobe'
c729caf6
C
15import { VideoResolution, VideoTranscodingFPS } from '@shared/models'
16import { CONFIG } from '../../initializers/config'
17import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
18import { logger } from '../logger'
daf6e480 19
6b67897e
C
20/**
21 *
22 * Helpers to run ffprobe and extract data from the JSON output
23 *
24 */
25
c729caf6
C
26// ---------------------------------------------------------------------------
27// Codecs
28// ---------------------------------------------------------------------------
daf6e480 29
c729caf6
C
30async function getVideoStreamCodec (path: string) {
31 const videoStream = await getVideoStream(path)
daf6e480
C
32 if (!videoStream) return ''
33
34 const videoCodec = videoStream.codec_tag_string
35
78995146 36 if (videoCodec === 'vp09') return 'vp09.00.50.08'
08370f62 37 if (videoCodec === 'hev1') return 'hev1.1.6.L93.B0'
78995146 38
daf6e480 39 const baseProfileMatrix = {
78995146
C
40 avc1: {
41 High: '6400',
42 Main: '4D40',
43 Baseline: '42E0'
44 },
45 av01: {
46 High: '1',
47 Main: '0',
48 Professional: '2'
49 }
daf6e480
C
50 }
51
78995146 52 let baseProfile = baseProfileMatrix[videoCodec][videoStream.profile]
daf6e480
C
53 if (!baseProfile) {
54 logger.warn('Cannot get video profile codec of %s.', path, { videoStream })
78995146
C
55 baseProfile = baseProfileMatrix[videoCodec]['High'] // Fallback
56 }
57
58 if (videoCodec === 'av01') {
59 const level = videoStream.level
60
61 // Guess the tier indicator and bit depth
62 return `${videoCodec}.${baseProfile}.${level}M.08`
daf6e480
C
63 }
64
78995146 65 // Default, h264 codec
daf6e480
C
66 let level = videoStream.level.toString(16)
67 if (level.length === 1) level = `0${level}`
68
69 return `${videoCodec}.${baseProfile}${level}`
70}
71
41fb13c3 72async function getAudioStreamCodec (path: string, existingProbe?: FfprobeData) {
daf6e480
C
73 const { audioStream } = await getAudioStream(path, existingProbe)
74
75 if (!audioStream) return ''
76
78995146
C
77 const audioCodecName = audioStream.codec_name
78
79 if (audioCodecName === 'opus') return 'opus'
80 if (audioCodecName === 'vorbis') return 'vorbis'
81 if (audioCodecName === 'aac') return 'mp4a.40.2'
3d401c1b 82 if (audioCodecName === 'mp3') return 'mp4a.40.34'
daf6e480
C
83
84 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
85
86 return 'mp4a.40.2' // Fallback
87}
88
c729caf6
C
89// ---------------------------------------------------------------------------
90// Resolutions
91// ---------------------------------------------------------------------------
92
84cae54e 93function computeResolutionsToTranscode (options: {
5e2afe42 94 input: number
84cae54e 95 type: 'vod' | 'live'
5e2afe42
C
96 includeInput: boolean
97 strictLower: boolean
84cae54e 98}) {
5e2afe42 99 const { input, type, includeInput, strictLower } = options
84cae54e 100
daf6e480
C
101 const configResolutions = type === 'vod'
102 ? CONFIG.TRANSCODING.RESOLUTIONS
103 : CONFIG.LIVE.TRANSCODING.RESOLUTIONS
104
84cae54e 105 const resolutionsEnabled = new Set<number>()
daf6e480
C
106
107 // Put in the order we want to proceed jobs
84cae54e 108 const availableResolutions: VideoResolution[] = [
daf6e480
C
109 VideoResolution.H_NOVIDEO,
110 VideoResolution.H_480P,
111 VideoResolution.H_360P,
112 VideoResolution.H_720P,
113 VideoResolution.H_240P,
8dd754c7 114 VideoResolution.H_144P,
daf6e480 115 VideoResolution.H_1080P,
b7085c71 116 VideoResolution.H_1440P,
daf6e480
C
117 VideoResolution.H_4K
118 ]
119
84cae54e 120 for (const resolution of availableResolutions) {
5e2afe42
C
121 // Resolution not enabled
122 if (configResolutions[resolution + 'p'] !== true) continue
123 // Too big resolution for input file
124 if (input < resolution) continue
125 // We only want lower resolutions than input file
126 if (strictLower && input === resolution) continue
127
128 resolutionsEnabled.add(resolution)
daf6e480
C
129 }
130
5e2afe42
C
131 if (includeInput) {
132 resolutionsEnabled.add(input)
84cae54e
C
133 }
134
135 return Array.from(resolutionsEnabled)
daf6e480
C
136}
137
c729caf6
C
138// ---------------------------------------------------------------------------
139// Can quick transcode
140// ---------------------------------------------------------------------------
141
daf6e480 142async function canDoQuickTranscode (path: string): Promise<boolean> {
ffd970fa
C
143 if (CONFIG.TRANSCODING.PROFILE !== 'default') return false
144
daf6e480
C
145 const probe = await ffprobePromise(path)
146
5a547f69
C
147 return await canDoQuickVideoTranscode(path, probe) &&
148 await canDoQuickAudioTranscode(path, probe)
149}
150
c729caf6
C
151async function canDoQuickAudioTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
152 const parsedAudio = await getAudioStream(path, probe)
153
154 if (!parsedAudio.audioStream) return true
155
156 if (parsedAudio.audioStream['codec_name'] !== 'aac') return false
157
158 const audioBitrate = parsedAudio.bitrate
159 if (!audioBitrate) return false
160
161 const maxAudioBitrate = getMaxAudioBitrate('aac', audioBitrate)
162 if (maxAudioBitrate !== -1 && audioBitrate > maxAudioBitrate) return false
163
164 const channelLayout = parsedAudio.audioStream['channel_layout']
165 // Causes playback issues with Chrome
4fd6dcfb 166 if (!channelLayout || channelLayout === 'unknown' || channelLayout === 'quad') return false
c729caf6
C
167
168 return true
169}
170
41fb13c3 171async function canDoQuickVideoTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
c729caf6
C
172 const videoStream = await getVideoStream(path, probe)
173 const fps = await getVideoStreamFPS(path, probe)
174 const bitRate = await getVideoStreamBitrate(path, probe)
175 const resolutionData = await getVideoStreamDimensionsInfo(path, probe)
daf6e480 176
33ff70ba
C
177 // If ffprobe did not manage to guess the bitrate
178 if (!bitRate) return false
179
daf6e480 180 // check video params
c729caf6 181 if (!videoStream) return false
daf6e480
C
182 if (videoStream['codec_name'] !== 'h264') return false
183 if (videoStream['pix_fmt'] !== 'yuv420p') return false
184 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
679c12e6 185 if (bitRate > getMaxBitrate({ ...resolutionData, fps })) return false
daf6e480 186
5a547f69
C
187 return true
188}
189
c729caf6
C
190// ---------------------------------------------------------------------------
191// Framerate
192// ---------------------------------------------------------------------------
193
679c12e6 194function getClosestFramerateStandard <K extends keyof Pick<VideoTranscodingFPS, 'HD_STANDARD' | 'STANDARD'>> (fps: number, type: K) {
daf6e480
C
195 return VIDEO_TRANSCODING_FPS[type].slice(0)
196 .sort((a, b) => fps % a - fps % b)[0]
197}
198
884d2c39
C
199function computeFPS (fpsArg: number, resolution: VideoResolution) {
200 let fps = fpsArg
201
202 if (
203 // On small/medium resolutions, limit FPS
204 resolution !== undefined &&
205 resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
206 fps > VIDEO_TRANSCODING_FPS.AVERAGE
207 ) {
208 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
209 fps = getClosestFramerateStandard(fps, 'STANDARD')
210 }
211
212 // Hard FPS limits
213 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
f7bb2bb5
C
214
215 if (fps < VIDEO_TRANSCODING_FPS.MIN) {
216 throw new Error(`Cannot compute FPS because ${fps} is lower than our minimum value ${VIDEO_TRANSCODING_FPS.MIN}`)
217 }
884d2c39
C
218
219 return fps
220}
221
daf6e480
C
222// ---------------------------------------------------------------------------
223
224export {
c729caf6
C
225 // Re export ffprobe utils
226 getVideoStreamDimensionsInfo,
227 buildFileMetadata,
daf6e480 228 getMaxAudioBitrate,
c729caf6
C
229 getVideoStream,
230 getVideoStreamDuration,
daf6e480 231 getAudioStream,
c729caf6
C
232 hasAudioStream,
233 getVideoStreamFPS,
5a547f69 234 ffprobePromise,
c729caf6
C
235 getVideoStreamBitrate,
236
237 getVideoStreamCodec,
238 getAudioStreamCodec,
239
240 computeFPS,
daf6e480 241 getClosestFramerateStandard,
c729caf6 242
84cae54e 243 computeResolutionsToTranscode,
c729caf6 244
5a547f69
C
245 canDoQuickTranscode,
246 canDoQuickVideoTranscode,
247 canDoQuickAudioTranscode
daf6e480 248}