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