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,
25 for (const resolution of resolutions) {
26 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
27 resolutionsEnabled.push(resolution)
31 return resolutionsEnabled
34 async function getVideoFileSize (path: string) {
35 const videoStream = await getVideoStreamFromFile(path)
38 width: videoStream.width,
39 height: videoStream.height
43 async function getVideoFileResolution (path: string) {
44 const size = await getVideoFileSize(path)
47 videoFileResolution: Math.min(size.height, size.width),
48 isPortraitMode: size.height > size.width
52 async function getVideoFileFPS (path: string) {
53 const videoStream = await getVideoStreamFromFile(path)
55 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
56 const valuesText: string = videoStream[key]
57 if (!valuesText) continue
59 const [ frames, seconds ] = valuesText.split('/')
60 if (!frames || !seconds) continue
62 const result = parseInt(frames, 10) / parseInt(seconds, 10)
63 if (result > 0) return Math.round(result)
69 async function getVideoFileBitrate (path: string) {
70 return new Promise<number>((res, rej) => {
71 ffmpeg.ffprobe(path, (err, metadata) => {
72 if (err) return rej(err)
74 return res(metadata.format.bit_rate)
79 function getDurationFromVideoFile (path: string) {
80 return new Promise<number>((res, rej) => {
81 ffmpeg.ffprobe(path, (err, metadata) => {
82 if (err) return rej(err)
84 return res(Math.floor(metadata.format.duration))
89 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
90 const pendingImageName = 'pending-' + imageName
93 filename: pendingImageName,
98 const pendingImagePath = join(folder, pendingImageName)
101 await new Promise<string>((res, rej) => {
102 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
104 .on('end', () => res(imageName))
108 const destination = join(folder, imageName)
109 await processImage(pendingImagePath, destination, size)
111 logger.error('Cannot generate image from video %s.', fromPath, { err })
114 await remove(pendingImagePath)
116 logger.debug('Cannot remove pending image path after generation error.', { err })
121 type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio'
123 interface BaseTranscodeOptions {
124 type: TranscodeOptionsType
127 resolution: VideoResolution
128 isPortraitMode?: boolean
131 interface HLSTranscodeOptions extends BaseTranscodeOptions {
134 videoFilename: string
138 interface QuickTranscodeOptions extends BaseTranscodeOptions {
139 type: 'quick-transcode'
142 interface VideoTranscodeOptions extends BaseTranscodeOptions {
146 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
151 type TranscodeOptions = HLSTranscodeOptions | VideoTranscodeOptions | MergeAudioTranscodeOptions | QuickTranscodeOptions
153 function transcode (options: TranscodeOptions) {
154 return new Promise<void>(async (res, rej) => {
156 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
157 .output(options.outputPath)
159 if (options.type === 'quick-transcode') {
160 command = await buildQuickTranscodeCommand(command)
161 } else if (options.type === 'hls') {
162 command = await buildHLSCommand(command, options)
163 } else if (options.type === 'merge-audio') {
164 command = await buildAudioMergeCommand(command, options)
166 command = await buildx264Command(command, options)
169 if (CONFIG.TRANSCODING.THREADS > 0) {
170 // if we don't set any threads ffmpeg will chose automatically
171 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
175 .on('error', (err, stdout, stderr) => {
176 logger.error('Error in transcoding job.', { stdout, stderr })
180 return fixHLSPlaylistIfNeeded(options)
182 .catch(err => rej(err))
191 async function canDoQuickTranscode (path: string): Promise<boolean> {
192 // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
193 const videoStream = await getVideoStreamFromFile(path)
194 const parsedAudio = await audio.get(path)
195 const fps = await getVideoFileFPS(path)
196 const bitRate = await getVideoFileBitrate(path)
197 const resolution = await getVideoFileResolution(path)
199 // check video params
200 if (videoStream[ 'codec_name' ] !== 'h264') return false
201 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
202 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
204 // check audio params (if audio stream exists)
205 if (parsedAudio.audioStream) {
206 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
208 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
209 if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
215 // ---------------------------------------------------------------------------
219 getVideoFileResolution,
220 getDurationFromVideoFile,
221 generateImageFromVideoFile,
223 TranscodeOptionsType,
226 computeResolutionsToTranscode,
232 // ---------------------------------------------------------------------------
234 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: VideoTranscodeOptions) {
235 let fps = await getVideoFileFPS(options.inputPath)
236 // On small/medium resolutions, limit FPS
238 options.resolution !== undefined &&
239 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
240 fps > VIDEO_TRANSCODING_FPS.AVERAGE
242 fps = VIDEO_TRANSCODING_FPS.AVERAGE
245 command = await presetH264(command, options.inputPath, options.resolution, fps)
247 if (options.resolution !== undefined) {
248 // '?x720' or '720x?' for example
249 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
250 command = command.size(size)
255 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
256 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
258 command = command.withFPS(fps)
264 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
265 command = command.loop(undefined)
267 command = await presetH264VeryFast(command, options.audioPath, options.resolution)
269 command = command.input(options.audioPath)
270 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
271 .outputOption('-tune stillimage')
272 .outputOption('-shortest')
277 async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
278 command = await presetCopy(command)
280 command = command.outputOption('-map_metadata -1') // strip all metadata
281 .outputOption('-movflags faststart')
286 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
287 const videoPath = getHLSVideoPath(options)
289 command = await presetCopy(command)
291 command = command.outputOption('-hls_time 4')
292 .outputOption('-hls_list_size 0')
293 .outputOption('-hls_playlist_type vod')
294 .outputOption('-hls_segment_filename ' + videoPath)
295 .outputOption('-hls_segment_type fmp4')
296 .outputOption('-f hls')
297 .outputOption('-hls_flags single_file')
302 function getHLSVideoPath (options: HLSTranscodeOptions) {
303 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
306 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
307 if (options.type !== 'hls') return
309 const fileContent = await readFile(options.outputPath)
311 const videoFileName = options.hlsPlaylist.videoFilename
312 const videoFilePath = getHLSVideoPath(options)
314 // Fix wrong mapping with some ffmpeg versions
315 const newContent = fileContent.toString()
316 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
318 await writeFile(options.outputPath, newContent)
321 function getVideoStreamFromFile (path: string) {
322 return new Promise<any>((res, rej) => {
323 ffmpeg.ffprobe(path, (err, metadata) => {
324 if (err) return rej(err)
326 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
327 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
329 return res(videoStream)
335 * A slightly customised version of the 'veryfast' x264 preset
337 * The veryfast preset is right in the sweet spot of performance
338 * and quality. Superfast and ultrafast will give you better
339 * performance, but then quality is noticeably worse.
341 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
342 let localCommand = await presetH264(command, input, resolution, fps)
344 localCommand = localCommand.outputOption('-preset:v veryfast')
347 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
348 Our target situation is closer to a livestream than a stream,
349 since we want to reduce as much a possible the encoding burden,
350 although not to the point of a livestream where there is a hard
351 constraint on the frames per second to be encoded.
358 * A toolbox to play with audio
361 export const get = (option: string) => {
362 // without position, ffprobe considers the last input only
363 // we make it consider the first input only
364 // if you pass a file path to pos, then ffprobe acts on that file directly
365 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
367 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
368 if (err) return rej(err)
370 if ('streams' in data) {
371 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
374 absolutePath: data.format.filename,
380 return res({ absolutePath: data.format.filename })
383 return ffmpeg.ffprobe(option, parseFfprobe)
387 export namespace bitrate {
388 const baseKbitrate = 384
390 const toBits = (kbits: number): number => { return kbits * 8000 }
392 export const aac = (bitrate: number): number => {
394 case bitrate > toBits(baseKbitrate):
397 return -1 // we interpret it as a signal to copy the audio stream as is
401 export const mp3 = (bitrate: number): number => {
403 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
404 That's why, when using aac, we can go to lower kbit/sec. The equivalences
405 made here are not made to be accurate, especially with good mp3 encoders.
408 case bitrate <= toBits(192):
410 case bitrate <= toBits(384):
420 * Standard profile, with variable bitrate audio and faststart.
422 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
423 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
425 async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
426 let localCommand = command
428 .videoCodec('libx264')
429 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
430 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
431 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
432 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
433 .outputOption('-map_metadata -1') // strip all metadata
434 .outputOption('-movflags faststart')
436 const parsedAudio = await audio.get(input)
438 if (!parsedAudio.audioStream) {
439 localCommand = localCommand.noAudio()
440 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
441 localCommand = localCommand
442 .audioCodec('libfdk_aac')
445 // we try to reduce the ceiling bitrate by making rough matches of bitrates
446 // of course this is far from perfect, but it might save some space in the end
447 localCommand = localCommand.audioCodec('aac')
449 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
451 if (audio.bitrate[ audioCodecName ]) {
452 const bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
453 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
458 // Constrained Encoding (VBV)
459 // https://slhck.info/video/2017/03/01/rate-control.html
460 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
461 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
462 localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
464 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
465 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
466 // https://superuser.com/a/908325
467 localCommand = localCommand.outputOption(`-g ${fps * 2}`)
473 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {