]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg-utils.ts
Update E2E tests
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
CommitLineData
14d3270f 1import * as ffmpeg from 'fluent-ffmpeg'
09209296 2import { dirname, join } from 'path'
cdf4cb9e 3import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
d175a6f7 4import { CONFIG, FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers/constants'
26670720 5import { processImage } from './image-utils'
6fdc553a 6import { logger } from './logger'
e5565833 7import { checkFFmpegEncoders } from '../initializers/checker-before-init'
7f8f8bdb 8import { remove, readFile, writeFile } from 'fs-extra'
14d3270f 9
06215f15
C
10function computeResolutionsToTranscode (videoFileHeight: number) {
11 const resolutionsEnabled: number[] = []
12 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
13
14 // Put in the order we want to proceed jobs
15 const resolutions = [
16 VideoResolution.H_480P,
17 VideoResolution.H_360P,
18 VideoResolution.H_720P,
19 VideoResolution.H_240P,
20 VideoResolution.H_1080P
21 ]
22
23 for (const resolution of resolutions) {
24 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
25 resolutionsEnabled.push(resolution)
26 }
27 }
28
29 return resolutionsEnabled
30}
31
09209296 32async function getVideoFileSize (path: string) {
73c69591 33 const videoStream = await getVideoFileStream(path)
056aa7f2
C
34
35 return {
09209296
C
36 width: videoStream.width,
37 height: videoStream.height
38 }
39}
40
41async function getVideoFileResolution (path: string) {
42 const size = await getVideoFileSize(path)
43
44 return {
45 videoFileResolution: Math.min(size.height, size.width),
46 isPortraitMode: size.height > size.width
056aa7f2 47 }
73c69591 48}
14d3270f 49
73c69591
C
50async function getVideoFileFPS (path: string) {
51 const videoStream = await getVideoFileStream(path)
52
ef04ae20 53 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
73c69591
C
54 const valuesText: string = videoStream[key]
55 if (!valuesText) continue
56
57 const [ frames, seconds ] = valuesText.split('/')
58 if (!frames || !seconds) continue
59
60 const result = parseInt(frames, 10) / parseInt(seconds, 10)
3a6f351b 61 if (result > 0) return Math.round(result)
73c69591
C
62 }
63
64 return 0
14d3270f
C
65}
66
edb4ffc7
FA
67async function getVideoFileBitrate (path: string) {
68 return new Promise<number>((res, rej) => {
69 ffmpeg.ffprobe(path, (err, metadata) => {
70 if (err) return rej(err)
71
72 return res(metadata.format.bit_rate)
73 })
74 })
75}
76
14d3270f
C
77function getDurationFromVideoFile (path: string) {
78 return new Promise<number>((res, rej) => {
79 ffmpeg.ffprobe(path, (err, metadata) => {
80 if (err) return rej(err)
81
82 return res(Math.floor(metadata.format.duration))
83 })
84 })
85}
86
26670720
C
87async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
88 const pendingImageName = 'pending-' + imageName
89
14d3270f 90 const options = {
26670720 91 filename: pendingImageName,
14d3270f
C
92 count: 1,
93 folder
94 }
95
26670720 96 const pendingImagePath = join(folder, pendingImageName)
6fdc553a
C
97
98 try {
99 await new Promise<string>((res, rej) => {
7160878c 100 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
6fdc553a
C
101 .on('error', rej)
102 .on('end', () => res(imageName))
103 .thumbnail(options)
104 })
105
106 const destination = join(folder, imageName)
107 await processImage({ path: pendingImagePath }, destination, size)
108 } catch (err) {
d5b7d911 109 logger.error('Cannot generate image from video %s.', fromPath, { err })
6fdc553a
C
110
111 try {
62689b94 112 await remove(pendingImagePath)
6fdc553a 113 } catch (err) {
d5b7d911 114 logger.debug('Cannot remove pending image path after generation error.', { err })
6fdc553a
C
115 }
116 }
14d3270f
C
117}
118
119type TranscodeOptions = {
120 inputPath: string
121 outputPath: string
09209296 122 resolution: VideoResolution
056aa7f2 123 isPortraitMode?: boolean
09209296 124
4c280004
C
125 hlsPlaylist?: {
126 videoFilename: string
127 }
14d3270f
C
128}
129
130function transcode (options: TranscodeOptions) {
73c69591 131 return new Promise<void>(async (res, rej) => {
cdf4cb9e
C
132 try {
133 let fps = await getVideoFileFPS(options.inputPath)
134 // On small/medium resolutions, limit FPS
135 if (
136 options.resolution !== undefined &&
137 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
138 fps > VIDEO_TRANSCODING_FPS.AVERAGE
139 ) {
140 fps = VIDEO_TRANSCODING_FPS.AVERAGE
141 }
bcf21a37 142
cdf4cb9e
C
143 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
144 .output(options.outputPath)
145 command = await presetH264(command, options.resolution, fps)
7160878c 146
cdf4cb9e
C
147 if (CONFIG.TRANSCODING.THREADS > 0) {
148 // if we don't set any threads ffmpeg will chose automatically
149 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
150 }
14d3270f 151
cdf4cb9e
C
152 if (options.resolution !== undefined) {
153 // '?x720' or '720x?' for example
154 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
155 command = command.size(size)
156 }
3a6f351b 157
cdf4cb9e
C
158 if (fps) {
159 // Hard FPS limits
160 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
161 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
3a6f351b 162
cdf4cb9e
C
163 command = command.withFPS(fps)
164 }
14d3270f 165
4c280004 166 if (options.hlsPlaylist) {
7f8f8bdb 167 const videoPath = getHLSVideoPath(options)
09209296
C
168
169 command = command.outputOption('-hls_time 4')
170 .outputOption('-hls_list_size 0')
171 .outputOption('-hls_playlist_type vod')
4c280004
C
172 .outputOption('-hls_segment_filename ' + videoPath)
173 .outputOption('-hls_segment_type fmp4')
09209296 174 .outputOption('-f hls')
4c280004 175 .outputOption('-hls_flags single_file')
09209296
C
176 }
177
cdf4cb9e
C
178 command
179 .on('error', (err, stdout, stderr) => {
180 logger.error('Error in transcoding job.', { stdout, stderr })
181 return rej(err)
182 })
7f8f8bdb
C
183 .on('end', () => {
184 return onTranscodingSuccess(options)
185 .then(() => res())
186 .catch(err => rej(err))
187 })
cdf4cb9e
C
188 .run()
189 } catch (err) {
190 return rej(err)
191 }
14d3270f
C
192 })
193}
194
195// ---------------------------------------------------------------------------
196
197export {
09209296 198 getVideoFileSize,
056aa7f2 199 getVideoFileResolution,
14d3270f
C
200 getDurationFromVideoFile,
201 generateImageFromVideoFile,
73c69591 202 transcode,
7160878c 203 getVideoFileFPS,
06215f15 204 computeResolutionsToTranscode,
edb4ffc7
FA
205 audio,
206 getVideoFileBitrate
73c69591
C
207}
208
209// ---------------------------------------------------------------------------
210
7f8f8bdb
C
211function getHLSVideoPath (options: TranscodeOptions) {
212 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
213}
214
215async function onTranscodingSuccess (options: TranscodeOptions) {
216 if (!options.hlsPlaylist) return
217
218 // Fix wrong mapping with some ffmpeg versions
219 const fileContent = await readFile(options.outputPath)
220
221 const videoFileName = options.hlsPlaylist.videoFilename
222 const videoFilePath = getHLSVideoPath(options)
223
224 const newContent = fileContent.toString()
225 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
226
227 await writeFile(options.outputPath, newContent)
228}
229
73c69591
C
230function getVideoFileStream (path: string) {
231 return new Promise<any>((res, rej) => {
232 ffmpeg.ffprobe(path, (err, metadata) => {
233 if (err) return rej(err)
234
235 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
9ecac97b 236 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
73c69591
C
237
238 return res(videoStream)
239 })
240 })
14d3270f 241}
4176e227
RK
242
243/**
244 * A slightly customised version of the 'veryfast' x264 preset
245 *
246 * The veryfast preset is right in the sweet spot of performance
247 * and quality. Superfast and ultrafast will give you better
248 * performance, but then quality is noticeably worse.
249 */
cdf4cb9e
C
250async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
251 let localCommand = await presetH264(command, resolution, fps)
252 localCommand = localCommand.outputOption('-preset:v veryfast')
253 .outputOption([ '--aq-mode=2', '--aq-strength=1.3' ])
4176e227
RK
254 /*
255 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
256 Our target situation is closer to a livestream than a stream,
257 since we want to reduce as much a possible the encoding burden,
258 altough not to the point of a livestream where there is a hard
259 constraint on the frames per second to be encoded.
260
261 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
262 Make up for most of the loss of grain and macroblocking
263 with less computing power.
264 */
cdf4cb9e
C
265
266 return localCommand
4176e227
RK
267}
268
269/**
270 * A preset optimised for a stillimage audio video
271 */
cdf4cb9e
C
272async function presetStillImageWithAudio (
273 command: ffmpeg.FfmpegCommand,
274 resolution: VideoResolution,
275 fps: number
276): Promise<ffmpeg.FfmpegCommand> {
277 let localCommand = await presetH264VeryFast(command, resolution, fps)
278 localCommand = localCommand.outputOption('-tune stillimage')
279
280 return localCommand
4176e227
RK
281}
282
283/**
284 * A toolbox to play with audio
285 */
286namespace audio {
cdf4cb9e 287 export const get = (option: ffmpeg.FfmpegCommand | string) => {
4176e227
RK
288 // without position, ffprobe considers the last input only
289 // we make it consider the first input only
4a5ccac5 290 // if you pass a file path to pos, then ffprobe acts on that file directly
7160878c 291 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
cdf4cb9e
C
292
293 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
7160878c
RK
294 if (err) return rej(err)
295
296 if ('streams' in data) {
cdf4cb9e 297 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
7160878c
RK
298 if (audioStream) {
299 return res({
300 absolutePath: data.format.filename,
301 audioStream
302 })
4a5ccac5 303 }
7160878c 304 }
cdf4cb9e 305
7160878c 306 return res({ absolutePath: data.format.filename })
cdf4cb9e
C
307 }
308
309 if (typeof option === 'string') {
310 return ffmpeg.ffprobe(option, parseFfprobe)
311 }
312
313 return option.ffprobe(parseFfprobe)
4a5ccac5 314 })
4176e227
RK
315 }
316
317 export namespace bitrate {
eed24d26 318 const baseKbitrate = 384
4176e227
RK
319
320 const toBits = (kbits: number): number => { return kbits * 8000 }
321
322 export const aac = (bitrate: number): number => {
323 switch (true) {
7160878c 324 case bitrate > toBits(baseKbitrate):
4176e227
RK
325 return baseKbitrate
326 default:
327 return -1 // we interpret it as a signal to copy the audio stream as is
328 }
329 }
330
331 export const mp3 = (bitrate: number): number => {
7160878c
RK
332 /*
333 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
334 That's why, when using aac, we can go to lower kbit/sec. The equivalences
335 made here are not made to be accurate, especially with good mp3 encoders.
336 */
4176e227
RK
337 switch (true) {
338 case bitrate <= toBits(192):
339 return 128
340 case bitrate <= toBits(384):
341 return 256
342 default:
343 return baseKbitrate
344 }
345 }
346 }
347}
348
349/**
350 * Standard profile, with variable bitrate audio and faststart.
351 *
352 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
353 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
354 */
cdf4cb9e
C
355async function presetH264 (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
356 let localCommand = command
4176e227
RK
357 .format('mp4')
358 .videoCodec('libx264')
359 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
360 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
361 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
408f50eb 362 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
4a5ccac5 363 .outputOption('-map_metadata -1') // strip all metadata
4176e227 364 .outputOption('-movflags faststart')
4176e227 365
cdf4cb9e 366 const parsedAudio = await audio.get(localCommand)
4176e227 367
cdf4cb9e
C
368 if (!parsedAudio.audioStream) {
369 localCommand = localCommand.noAudio()
370 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
371 localCommand = localCommand
4176e227
RK
372 .audioCodec('libfdk_aac')
373 .audioQuality(5)
cdf4cb9e
C
374 } else {
375 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
376 // of course this is far from perfect, but it might save some space in the end
377 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
378 let bitrate: number
379 if (audio.bitrate[ audioCodecName ]) {
64e3e270 380 localCommand = localCommand.audioCodec('aac')
cdf4cb9e 381
64e3e270
C
382 bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
383 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
cdf4cb9e 384 }
4176e227
RK
385 }
386
bcf21a37
FA
387 // Constrained Encoding (VBV)
388 // https://slhck.info/video/2017/03/01/rate-control.html
389 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
390 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
cdf4cb9e 391 localCommand = localCommand.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
bcf21a37
FA
392
393 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
394 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
395 // https://superuser.com/a/908325
cdf4cb9e 396 localCommand = localCommand.outputOption(`-g ${ fps * 2 }`)
bcf21a37 397
cdf4cb9e 398 return localCommand
4176e227 399}