]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg-utils.ts
improve description of the HTTP video import feature
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
CommitLineData
14d3270f 1import * as ffmpeg from 'fluent-ffmpeg'
6fdc553a 2import { join } from 'path'
edb4ffc7 3import { VideoResolution, getTargetBitrate } from '../../shared/models/videos'
62689b94 4import { CONFIG, FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers'
26670720 5import { processImage } from './image-utils'
6fdc553a 6import { logger } from './logger'
e5565833 7import { checkFFmpegEncoders } from '../initializers/checker-before-init'
62689b94 8import { remove } 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
056aa7f2 32async function getVideoFileResolution (path: string) {
73c69591 33 const videoStream = await getVideoFileStream(path)
056aa7f2
C
34
35 return {
36 videoFileResolution: Math.min(videoStream.height, videoStream.width),
37 isPortraitMode: videoStream.height > videoStream.width
38 }
73c69591 39}
14d3270f 40
73c69591
C
41async function getVideoFileFPS (path: string) {
42 const videoStream = await getVideoFileStream(path)
43
44 for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
45 const valuesText: string = videoStream[key]
46 if (!valuesText) continue
47
48 const [ frames, seconds ] = valuesText.split('/')
49 if (!frames || !seconds) continue
50
51 const result = parseInt(frames, 10) / parseInt(seconds, 10)
3a6f351b 52 if (result > 0) return Math.round(result)
73c69591
C
53 }
54
55 return 0
14d3270f
C
56}
57
edb4ffc7
FA
58async function getVideoFileBitrate (path: string) {
59 return new Promise<number>((res, rej) => {
60 ffmpeg.ffprobe(path, (err, metadata) => {
61 if (err) return rej(err)
62
63 return res(metadata.format.bit_rate)
64 })
65 })
66}
67
14d3270f
C
68function getDurationFromVideoFile (path: string) {
69 return new Promise<number>((res, rej) => {
70 ffmpeg.ffprobe(path, (err, metadata) => {
71 if (err) return rej(err)
72
73 return res(Math.floor(metadata.format.duration))
74 })
75 })
76}
77
26670720
C
78async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
79 const pendingImageName = 'pending-' + imageName
80
14d3270f 81 const options = {
26670720 82 filename: pendingImageName,
14d3270f
C
83 count: 1,
84 folder
85 }
86
26670720 87 const pendingImagePath = join(folder, pendingImageName)
6fdc553a
C
88
89 try {
90 await new Promise<string>((res, rej) => {
7160878c 91 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
6fdc553a
C
92 .on('error', rej)
93 .on('end', () => res(imageName))
94 .thumbnail(options)
95 })
96
97 const destination = join(folder, imageName)
98 await processImage({ path: pendingImagePath }, destination, size)
99 } catch (err) {
d5b7d911 100 logger.error('Cannot generate image from video %s.', fromPath, { err })
6fdc553a
C
101
102 try {
62689b94 103 await remove(pendingImagePath)
6fdc553a 104 } catch (err) {
d5b7d911 105 logger.debug('Cannot remove pending image path after generation error.', { err })
6fdc553a
C
106 }
107 }
14d3270f
C
108}
109
110type TranscodeOptions = {
111 inputPath: string
112 outputPath: string
113 resolution?: VideoResolution
056aa7f2 114 isPortraitMode?: boolean
14d3270f
C
115}
116
117function transcode (options: TranscodeOptions) {
73c69591 118 return new Promise<void>(async (res, rej) => {
7160878c 119 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
14d3270f 120 .output(options.outputPath)
19ca8ca9 121 .preset(standard)
7160878c 122
991feec9 123 if (CONFIG.TRANSCODING.THREADS > 0) {
7160878c
RK
124 // if we don't set any threads ffmpeg will chose automatically
125 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
991feec9 126 }
14d3270f 127
3a6f351b 128 let fps = await getVideoFileFPS(options.inputPath)
14d3270f 129 if (options.resolution !== undefined) {
056aa7f2
C
130 // '?x720' or '720x?' for example
131 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
14d3270f 132 command = command.size(size)
3a6f351b
C
133
134 // On small/medium resolutions, limit FPS
135 if (
136 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
137 fps > VIDEO_TRANSCODING_FPS.AVERAGE
138 ) {
139 fps = VIDEO_TRANSCODING_FPS.AVERAGE
140 }
141 }
142
143 if (fps) {
144 // Hard FPS limits
145 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
146 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
147
148 command = command.withFPS(fps)
14d3270f
C
149 }
150
edb4ffc7
FA
151 // Constrained Encoding (VBV)
152 // https://slhck.info/video/2017/03/01/rate-control.html
153 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
154 const targetBitrate = getTargetBitrate(options.resolution, fps, VIDEO_TRANSCODING_FPS)
e1d7b98b 155 command.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
edb4ffc7 156
747b2990
C
157 command
158 .on('error', (err, stdout, stderr) => {
159 logger.error('Error in transcoding job.', { stdout, stderr })
160 return rej(err)
161 })
162 .on('end', res)
163 .run()
14d3270f
C
164 })
165}
166
167// ---------------------------------------------------------------------------
168
169export {
056aa7f2 170 getVideoFileResolution,
14d3270f
C
171 getDurationFromVideoFile,
172 generateImageFromVideoFile,
73c69591 173 transcode,
7160878c 174 getVideoFileFPS,
06215f15 175 computeResolutionsToTranscode,
edb4ffc7
FA
176 audio,
177 getVideoFileBitrate
73c69591
C
178}
179
180// ---------------------------------------------------------------------------
181
182function getVideoFileStream (path: string) {
183 return new Promise<any>((res, rej) => {
184 ffmpeg.ffprobe(path, (err, metadata) => {
185 if (err) return rej(err)
186
187 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
188 if (!videoStream) throw new Error('Cannot find video stream of ' + path)
189
190 return res(videoStream)
191 })
192 })
14d3270f 193}
4176e227
RK
194
195/**
196 * A slightly customised version of the 'veryfast' x264 preset
197 *
198 * The veryfast preset is right in the sweet spot of performance
199 * and quality. Superfast and ultrafast will give you better
200 * performance, but then quality is noticeably worse.
201 */
4a5ccac5
RK
202function veryfast (_ffmpeg) {
203 _ffmpeg
4176e227
RK
204 .preset(standard)
205 .outputOption('-preset:v veryfast')
206 .outputOption(['--aq-mode=2', '--aq-strength=1.3'])
207 /*
208 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
209 Our target situation is closer to a livestream than a stream,
210 since we want to reduce as much a possible the encoding burden,
211 altough not to the point of a livestream where there is a hard
212 constraint on the frames per second to be encoded.
213
214 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
215 Make up for most of the loss of grain and macroblocking
216 with less computing power.
217 */
218}
219
220/**
221 * A preset optimised for a stillimage audio video
222 */
4a5ccac5
RK
223function audio (_ffmpeg) {
224 _ffmpeg
4176e227
RK
225 .preset(veryfast)
226 .outputOption('-tune stillimage')
227}
228
229/**
230 * A toolbox to play with audio
231 */
232namespace audio {
4a5ccac5 233 export const get = (_ffmpeg, pos: number | string = 0) => {
4176e227
RK
234 // without position, ffprobe considers the last input only
235 // we make it consider the first input only
4a5ccac5 236 // if you pass a file path to pos, then ffprobe acts on that file directly
7160878c
RK
237 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
238 _ffmpeg.ffprobe(pos, (err,data) => {
239 if (err) return rej(err)
240
241 if ('streams' in data) {
242 const audioStream = data['streams'].find(stream => stream['codec_type'] === 'audio')
243 if (audioStream) {
244 return res({
245 absolutePath: data.format.filename,
246 audioStream
247 })
4a5ccac5 248 }
7160878c
RK
249 }
250 return res({ absolutePath: data.format.filename })
251 })
4a5ccac5 252 })
4176e227
RK
253 }
254
255 export namespace bitrate {
eed24d26 256 const baseKbitrate = 384
4176e227
RK
257
258 const toBits = (kbits: number): number => { return kbits * 8000 }
259
260 export const aac = (bitrate: number): number => {
261 switch (true) {
7160878c 262 case bitrate > toBits(baseKbitrate):
4176e227
RK
263 return baseKbitrate
264 default:
265 return -1 // we interpret it as a signal to copy the audio stream as is
266 }
267 }
268
269 export const mp3 = (bitrate: number): number => {
7160878c
RK
270 /*
271 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
272 That's why, when using aac, we can go to lower kbit/sec. The equivalences
273 made here are not made to be accurate, especially with good mp3 encoders.
274 */
4176e227
RK
275 switch (true) {
276 case bitrate <= toBits(192):
277 return 128
278 case bitrate <= toBits(384):
279 return 256
280 default:
281 return baseKbitrate
282 }
283 }
284 }
285}
286
287/**
288 * Standard profile, with variable bitrate audio and faststart.
289 *
290 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
291 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
292 */
4a5ccac5 293async function standard (_ffmpeg) {
4a5ccac5 294 let localFfmpeg = _ffmpeg
4176e227
RK
295 .format('mp4')
296 .videoCodec('libx264')
297 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
298 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
299 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
4a5ccac5 300 .outputOption('-map_metadata -1') // strip all metadata
4176e227 301 .outputOption('-movflags faststart')
7160878c 302 const _audio = await audio.get(localFfmpeg)
4176e227 303
7160878c
RK
304 if (!_audio.audioStream) {
305 return localFfmpeg.noAudio()
306 }
4176e227 307
4176e227
RK
308 // we favor VBR, if a good AAC encoder is available
309 if ((await checkFFmpegEncoders()).get('libfdk_aac')) {
4a5ccac5 310 return localFfmpeg
4176e227
RK
311 .audioCodec('libfdk_aac')
312 .audioQuality(5)
313 }
314
eed24d26
C
315 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
316 // of course this is far from perfect, but it might save some space in the end
317 const audioCodecName = _audio.audioStream['codec_name']
318 let bitrate: number
319 if (audio.bitrate[audioCodecName]) {
320 bitrate = audio.bitrate[audioCodecName](_audio.audioStream['bit_rate'])
321
322 if (bitrate === -1) return localFfmpeg.audioCodec('copy')
323 }
324
325 if (bitrate !== undefined) return localFfmpeg.audioBitrate(bitrate)
326
327 return localFfmpeg
4176e227 328}