]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg/ffprobe-utils.ts
Fix running again transcoding on a video only file
[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
01ec3975 58 if (videoCodec === 'av01') {
31951bad
C
59 let level = videoStream.level.toString()
60 if (level.length === 1) level = `0${level}`
61
78995146
C
62 // Guess the tier indicator and bit depth
63 return `${videoCodec}.${baseProfile}.${level}M.08`
daf6e480
C
64 }
65
31951bad
C
66 let level = videoStream.level.toString(16)
67 if (level.length === 1) level = `0${level}`
68
78995146 69 // Default, h264 codec
daf6e480
C
70 return `${videoCodec}.${baseProfile}${level}`
71}
72
41fb13c3 73async function getAudioStreamCodec (path: string, existingProbe?: FfprobeData) {
daf6e480
C
74 const { audioStream } = await getAudioStream(path, existingProbe)
75
76 if (!audioStream) return ''
77
78995146
C
78 const audioCodecName = audioStream.codec_name
79
80 if (audioCodecName === 'opus') return 'opus'
81 if (audioCodecName === 'vorbis') return 'vorbis'
82 if (audioCodecName === 'aac') return 'mp4a.40.2'
3d401c1b 83 if (audioCodecName === 'mp3') return 'mp4a.40.34'
daf6e480
C
84
85 logger.warn('Cannot get audio codec of %s.', path, { audioStream })
86
87 return 'mp4a.40.2' // Fallback
88}
89
c729caf6
C
90// ---------------------------------------------------------------------------
91// Resolutions
92// ---------------------------------------------------------------------------
93
84cae54e 94function computeResolutionsToTranscode (options: {
5e2afe42 95 input: number
84cae54e 96 type: 'vod' | 'live'
5e2afe42
C
97 includeInput: boolean
98 strictLower: boolean
a32bf8cd 99 hasAudio: boolean
84cae54e 100}) {
a32bf8cd 101 const { input, type, includeInput, strictLower, hasAudio } = options
84cae54e 102
daf6e480
C
103 const configResolutions = type === 'vod'
104 ? CONFIG.TRANSCODING.RESOLUTIONS
105 : CONFIG.LIVE.TRANSCODING.RESOLUTIONS
106
84cae54e 107 const resolutionsEnabled = new Set<number>()
daf6e480
C
108
109 // Put in the order we want to proceed jobs
84cae54e 110 const availableResolutions: VideoResolution[] = [
daf6e480
C
111 VideoResolution.H_NOVIDEO,
112 VideoResolution.H_480P,
113 VideoResolution.H_360P,
114 VideoResolution.H_720P,
115 VideoResolution.H_240P,
8dd754c7 116 VideoResolution.H_144P,
daf6e480 117 VideoResolution.H_1080P,
b7085c71 118 VideoResolution.H_1440P,
daf6e480
C
119 VideoResolution.H_4K
120 ]
121
84cae54e 122 for (const resolution of availableResolutions) {
5e2afe42
C
123 // Resolution not enabled
124 if (configResolutions[resolution + 'p'] !== true) continue
125 // Too big resolution for input file
126 if (input < resolution) continue
127 // We only want lower resolutions than input file
128 if (strictLower && input === resolution) continue
a32bf8cd
C
129 // Audio resolutio but no audio in the video
130 if (resolution === VideoResolution.H_NOVIDEO && !hasAudio) continue
5e2afe42
C
131
132 resolutionsEnabled.add(resolution)
daf6e480
C
133 }
134
5e2afe42
C
135 if (includeInput) {
136 resolutionsEnabled.add(input)
84cae54e
C
137 }
138
139 return Array.from(resolutionsEnabled)
daf6e480
C
140}
141
c729caf6
C
142// ---------------------------------------------------------------------------
143// Can quick transcode
144// ---------------------------------------------------------------------------
145
daf6e480 146async function canDoQuickTranscode (path: string): Promise<boolean> {
ffd970fa
C
147 if (CONFIG.TRANSCODING.PROFILE !== 'default') return false
148
daf6e480
C
149 const probe = await ffprobePromise(path)
150
5a547f69
C
151 return await canDoQuickVideoTranscode(path, probe) &&
152 await canDoQuickAudioTranscode(path, probe)
153}
154
c729caf6
C
155async function canDoQuickAudioTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
156 const parsedAudio = await getAudioStream(path, probe)
157
158 if (!parsedAudio.audioStream) return true
159
160 if (parsedAudio.audioStream['codec_name'] !== 'aac') return false
161
162 const audioBitrate = parsedAudio.bitrate
163 if (!audioBitrate) return false
164
165 const maxAudioBitrate = getMaxAudioBitrate('aac', audioBitrate)
166 if (maxAudioBitrate !== -1 && audioBitrate > maxAudioBitrate) return false
167
168 const channelLayout = parsedAudio.audioStream['channel_layout']
169 // Causes playback issues with Chrome
4fd6dcfb 170 if (!channelLayout || channelLayout === 'unknown' || channelLayout === 'quad') return false
c729caf6
C
171
172 return true
173}
174
41fb13c3 175async function canDoQuickVideoTranscode (path: string, probe?: FfprobeData): Promise<boolean> {
c729caf6
C
176 const videoStream = await getVideoStream(path, probe)
177 const fps = await getVideoStreamFPS(path, probe)
178 const bitRate = await getVideoStreamBitrate(path, probe)
179 const resolutionData = await getVideoStreamDimensionsInfo(path, probe)
daf6e480 180
33ff70ba
C
181 // If ffprobe did not manage to guess the bitrate
182 if (!bitRate) return false
183
daf6e480 184 // check video params
c729caf6 185 if (!videoStream) return false
daf6e480
C
186 if (videoStream['codec_name'] !== 'h264') return false
187 if (videoStream['pix_fmt'] !== 'yuv420p') return false
188 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
679c12e6 189 if (bitRate > getMaxBitrate({ ...resolutionData, fps })) return false
daf6e480 190
5a547f69
C
191 return true
192}
193
c729caf6
C
194// ---------------------------------------------------------------------------
195// Framerate
196// ---------------------------------------------------------------------------
197
679c12e6 198function getClosestFramerateStandard <K extends keyof Pick<VideoTranscodingFPS, 'HD_STANDARD' | 'STANDARD'>> (fps: number, type: K) {
daf6e480
C
199 return VIDEO_TRANSCODING_FPS[type].slice(0)
200 .sort((a, b) => fps % a - fps % b)[0]
201}
202
884d2c39
C
203function computeFPS (fpsArg: number, resolution: VideoResolution) {
204 let fps = fpsArg
205
206 if (
207 // On small/medium resolutions, limit FPS
208 resolution !== undefined &&
209 resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
210 fps > VIDEO_TRANSCODING_FPS.AVERAGE
211 ) {
212 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
213 fps = getClosestFramerateStandard(fps, 'STANDARD')
214 }
215
216 // Hard FPS limits
217 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
f7bb2bb5
C
218
219 if (fps < VIDEO_TRANSCODING_FPS.MIN) {
220 throw new Error(`Cannot compute FPS because ${fps} is lower than our minimum value ${VIDEO_TRANSCODING_FPS.MIN}`)
221 }
884d2c39
C
222
223 return fps
224}
225
daf6e480
C
226// ---------------------------------------------------------------------------
227
228export {
c729caf6
C
229 // Re export ffprobe utils
230 getVideoStreamDimensionsInfo,
231 buildFileMetadata,
daf6e480 232 getMaxAudioBitrate,
c729caf6
C
233 getVideoStream,
234 getVideoStreamDuration,
daf6e480 235 getAudioStream,
c729caf6
C
236 hasAudioStream,
237 getVideoStreamFPS,
5a547f69 238 ffprobePromise,
c729caf6
C
239 getVideoStreamBitrate,
240
241 getVideoStreamCodec,
242 getAudioStreamCodec,
243
244 computeFPS,
daf6e480 245 getClosestFramerateStandard,
c729caf6 246
84cae54e 247 computeResolutionsToTranscode,
c729caf6 248
5a547f69
C
249 canDoQuickTranscode,
250 canDoQuickVideoTranscode,
251 canDoQuickAudioTranscode
daf6e480 252}