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 TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio'
122 interface BaseTranscodeOptions {
123 type: TranscodeOptionsType
126 resolution: VideoResolution
127 isPortraitMode?: boolean
130 interface HLSTranscodeOptions extends BaseTranscodeOptions {
133 videoFilename: string
137 interface QuickTranscodeOptions extends BaseTranscodeOptions {
138 type: 'quick-transcode'
141 interface VideoTranscodeOptions extends BaseTranscodeOptions {
145 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
150 type TranscodeOptions = HLSTranscodeOptions | VideoTranscodeOptions | MergeAudioTranscodeOptions | QuickTranscodeOptions
152 function transcode (options: TranscodeOptions) {
153 return new Promise<void>(async (res, rej) => {
155 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
156 .output(options.outputPath)
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)
165 command = await buildx264Command(command, options)
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)
174 .on('error', (err, stdout, stderr) => {
175 logger.error('Error in transcoding job.', { stdout, stderr })
179 return fixHLSPlaylistIfNeeded(options)
181 .catch(err => rej(err))
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)
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
203 // check audio params (if audio stream exists)
204 if (parsedAudio.audioStream) {
205 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
207 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
208 if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
214 // ---------------------------------------------------------------------------
218 getVideoFileResolution,
219 getDurationFromVideoFile,
220 generateImageFromVideoFile,
222 TranscodeOptionsType,
225 computeResolutionsToTranscode,
231 // ---------------------------------------------------------------------------
233 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: VideoTranscodeOptions) {
234 let fps = await getVideoFileFPS(options.inputPath)
235 // On small/medium resolutions, limit FPS
237 options.resolution !== undefined &&
238 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
239 fps > VIDEO_TRANSCODING_FPS.AVERAGE
241 fps = VIDEO_TRANSCODING_FPS.AVERAGE
244 command = await presetH264(command, options.inputPath, options.resolution, fps)
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)
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
257 command = command.withFPS(fps)
263 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
264 command = command.loop(undefined)
266 command = await presetH264VeryFast(command, options.audioPath, options.resolution)
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')
276 async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
277 command = await presetCopy(command)
279 command = command.outputOption('-map_metadata -1') // strip all metadata
280 .outputOption('-movflags faststart')
285 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
286 const videoPath = getHLSVideoPath(options)
288 command = await presetCopy(command)
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')
301 function getHLSVideoPath (options: HLSTranscodeOptions) {
302 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
305 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
306 if (options.type !== 'hls') return
308 const fileContent = await readFile(options.outputPath)
310 const videoFileName = options.hlsPlaylist.videoFilename
311 const videoFilePath = getHLSVideoPath(options)
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}",`)
317 await writeFile(options.outputPath, newContent)
320 function getVideoStreamFromFile (path: string) {
321 return new Promise<any>((res, rej) => {
322 ffmpeg.ffprobe(path, (err, metadata) => {
323 if (err) return rej(err)
325 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
326 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
328 return res(videoStream)
334 * A slightly customised version of the 'veryfast' x264 preset
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.
340 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
341 let localCommand = await presetH264(command, input, resolution, fps)
343 localCommand = localCommand.outputOption('-preset:v veryfast')
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.
357 * A toolbox to play with 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) => {
366 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
367 if (err) return rej(err)
369 if ('streams' in data) {
370 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
373 absolutePath: data.format.filename,
379 return res({ absolutePath: data.format.filename })
382 return ffmpeg.ffprobe(option, parseFfprobe)
386 export namespace bitrate {
387 const baseKbitrate = 384
389 const toBits = (kbits: number): number => { return kbits * 8000 }
391 export const aac = (bitrate: number): number => {
393 case bitrate > toBits(baseKbitrate):
396 return -1 // we interpret it as a signal to copy the audio stream as is
400 export const mp3 = (bitrate: number): number => {
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.
407 case bitrate <= toBits(192):
409 case bitrate <= toBits(384):
419 * Standard profile, with variable bitrate audio and faststart.
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
424 async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
425 let localCommand = command
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')
435 const parsedAudio = await audio.get(input)
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')
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')
448 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
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)
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}` ])
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}`)
472 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {