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'
11 function computeResolutionsToTranscode (videoFileHeight: number) {
12 const resolutionsEnabled: number[] = []
13 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
15 // Put in the order we want to proceed jobs
17 VideoResolution.H_480P,
18 VideoResolution.H_360P,
19 VideoResolution.H_720P,
20 VideoResolution.H_240P,
21 VideoResolution.H_1080P
24 for (const resolution of resolutions) {
25 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
26 resolutionsEnabled.push(resolution)
30 return resolutionsEnabled
33 async function getVideoFileSize (path: string) {
34 const videoStream = await getVideoStreamFromFile(path)
37 width: videoStream.width,
38 height: videoStream.height
42 async function getVideoFileResolution (path: string) {
43 const size = await getVideoFileSize(path)
46 videoFileResolution: Math.min(size.height, size.width),
47 isPortraitMode: size.height > size.width
51 async function getVideoFileFPS (path: string) {
52 const videoStream = await getVideoStreamFromFile(path)
54 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
55 const valuesText: string = videoStream[key]
56 if (!valuesText) continue
58 const [ frames, seconds ] = valuesText.split('/')
59 if (!frames || !seconds) continue
61 const result = parseInt(frames, 10) / parseInt(seconds, 10)
62 if (result > 0) return Math.round(result)
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)
73 return res(metadata.format.bit_rate)
78 function getDurationFromVideoFile (path: string) {
79 return new Promise<number>((res, rej) => {
80 ffmpeg.ffprobe(path, (err, metadata) => {
81 if (err) return rej(err)
83 return res(Math.floor(metadata.format.duration))
88 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
89 const pendingImageName = 'pending-' + imageName
92 filename: pendingImageName,
97 const pendingImagePath = join(folder, pendingImageName)
100 await new Promise<string>((res, rej) => {
101 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
103 .on('end', () => res(imageName))
107 const destination = join(folder, imageName)
108 await processImage(pendingImagePath, destination, size)
110 logger.error('Cannot generate image from video %s.', fromPath, { err })
113 await remove(pendingImagePath)
115 logger.debug('Cannot remove pending image path after generation error.', { err })
120 type TranscodeOptions = {
123 resolution: VideoResolution
124 isPortraitMode?: boolean
125 doQuickTranscode?: Boolean
128 videoFilename: string
132 function transcode (options: TranscodeOptions) {
133 return new Promise<void>(async (res, rej) => {
135 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
136 .output(options.outputPath)
138 if (options.doQuickTranscode) {
139 if (options.hlsPlaylist) {
140 throw(Error("Quick transcode and HLS can't be used at the same time"))
144 .addOption('-c:v copy')
145 .addOption('-c:a copy')
146 .outputOption('-map_metadata -1') // strip all metadata
147 .outputOption('-movflags faststart')
148 } else if (options.hlsPlaylist) {
149 command = await buildHLSCommand(command, options)
151 command = await buildx264Command(command, options)
154 if (CONFIG.TRANSCODING.THREADS > 0) {
155 // if we don't set any threads ffmpeg will chose automatically
156 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
160 .on('error', (err, stdout, stderr) => {
161 logger.error('Error in transcoding job.', { stdout, stderr })
165 return onTranscodingSuccess(options)
167 .catch(err => rej(err))
176 async function canDoQuickTranscode (path: string) {
177 // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
178 const videoStream = await getVideoStreamFromFile(path)
179 const parsedAudio = await audio.get(path)
180 const fps = await getVideoFileFPS(path)
181 const bitRate = await getVideoFileBitrate(path)
182 const resolution = await getVideoFileResolution(path)
184 // check video params
185 if (videoStream[ 'codec_name' ] !== 'h264')
187 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX)
189 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS))
192 // check audio params (if audio stream exists)
193 if (parsedAudio.audioStream) {
194 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac')
196 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
197 if (maxAudioBitrate != -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate)
204 // ---------------------------------------------------------------------------
208 getVideoFileResolution,
209 getDurationFromVideoFile,
210 generateImageFromVideoFile,
213 computeResolutionsToTranscode,
219 // ---------------------------------------------------------------------------
221 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
222 let fps = await getVideoFileFPS(options.inputPath)
223 // On small/medium resolutions, limit FPS
225 options.resolution !== undefined &&
226 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
227 fps > VIDEO_TRANSCODING_FPS.AVERAGE
229 fps = VIDEO_TRANSCODING_FPS.AVERAGE
232 command = await presetH264(command, options.resolution, fps)
234 if (options.resolution !== undefined) {
235 // '?x720' or '720x?' for example
236 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
237 command = command.size(size)
242 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
243 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
245 command = command.withFPS(fps)
251 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
252 const videoPath = getHLSVideoPath(options)
254 command = await presetCopy(command)
256 command = command.outputOption('-hls_time 4')
257 .outputOption('-hls_list_size 0')
258 .outputOption('-hls_playlist_type vod')
259 .outputOption('-hls_segment_filename ' + videoPath)
260 .outputOption('-hls_segment_type fmp4')
261 .outputOption('-f hls')
262 .outputOption('-hls_flags single_file')
267 function getHLSVideoPath (options: TranscodeOptions) {
268 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
271 async function onTranscodingSuccess (options: TranscodeOptions) {
272 if (!options.hlsPlaylist) return
274 // Fix wrong mapping with some ffmpeg versions
275 const fileContent = await readFile(options.outputPath)
277 const videoFileName = options.hlsPlaylist.videoFilename
278 const videoFilePath = getHLSVideoPath(options)
280 const newContent = fileContent.toString()
281 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
283 await writeFile(options.outputPath, newContent)
286 function getVideoStreamFromFile (path: string) {
287 return new Promise<any>((res, rej) => {
288 ffmpeg.ffprobe(path, (err, metadata) => {
289 if (err) return rej(err)
291 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
292 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
294 return res(videoStream)
300 * A slightly customised version of the 'veryfast' x264 preset
302 * The veryfast preset is right in the sweet spot of performance
303 * and quality. Superfast and ultrafast will give you better
304 * performance, but then quality is noticeably worse.
306 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
307 let localCommand = await presetH264(command, resolution, fps)
308 localCommand = localCommand.outputOption('-preset:v veryfast')
309 .outputOption([ '--aq-mode=2', '--aq-strength=1.3' ])
311 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
312 Our target situation is closer to a livestream than a stream,
313 since we want to reduce as much a possible the encoding burden,
314 altough not to the point of a livestream where there is a hard
315 constraint on the frames per second to be encoded.
317 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
318 Make up for most of the loss of grain and macroblocking
319 with less computing power.
326 * A preset optimised for a stillimage audio video
328 async function presetStillImageWithAudio (
329 command: ffmpeg.FfmpegCommand,
330 resolution: VideoResolution,
332 ): Promise<ffmpeg.FfmpegCommand> {
333 let localCommand = await presetH264VeryFast(command, resolution, fps)
334 localCommand = localCommand.outputOption('-tune stillimage')
340 * A toolbox to play with audio
343 export const get = (option: ffmpeg.FfmpegCommand | string) => {
344 // without position, ffprobe considers the last input only
345 // we make it consider the first input only
346 // if you pass a file path to pos, then ffprobe acts on that file directly
347 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
349 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
350 if (err) return rej(err)
352 if ('streams' in data) {
353 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
356 absolutePath: data.format.filename,
362 return res({ absolutePath: data.format.filename })
365 if (typeof option === 'string') {
366 return ffmpeg.ffprobe(option, parseFfprobe)
369 return option.ffprobe(parseFfprobe)
373 export namespace bitrate {
374 const baseKbitrate = 384
376 const toBits = (kbits: number): number => { return kbits * 8000 }
378 export const aac = (bitrate: number): number => {
380 case bitrate > toBits(baseKbitrate):
383 return -1 // we interpret it as a signal to copy the audio stream as is
387 export const mp3 = (bitrate: number): number => {
389 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
390 That's why, when using aac, we can go to lower kbit/sec. The equivalences
391 made here are not made to be accurate, especially with good mp3 encoders.
394 case bitrate <= toBits(192):
396 case bitrate <= toBits(384):
406 * Standard profile, with variable bitrate audio and faststart.
408 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
409 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
411 async function presetH264 (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
412 let localCommand = command
414 .videoCodec('libx264')
415 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
416 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
417 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
418 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
419 .outputOption('-map_metadata -1') // strip all metadata
420 .outputOption('-movflags faststart')
422 const parsedAudio = await audio.get(localCommand)
424 if (!parsedAudio.audioStream) {
425 localCommand = localCommand.noAudio()
426 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
427 localCommand = localCommand
428 .audioCodec('libfdk_aac')
431 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
432 // of course this is far from perfect, but it might save some space in the end
433 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
435 if (audio.bitrate[ audioCodecName ]) {
436 localCommand = localCommand.audioCodec('aac')
438 bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
439 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
443 // Constrained Encoding (VBV)
444 // https://slhck.info/video/2017/03/01/rate-control.html
445 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
446 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
447 localCommand = localCommand.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
449 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
450 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
451 // https://superuser.com/a/908325
452 localCommand = localCommand.outputOption(`-g ${ fps * 2 }`)
457 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {