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_NOVIDEO,
18 VideoResolution.H_480P,
19 VideoResolution.H_360P,
20 VideoResolution.H_720P,
21 VideoResolution.H_240P,
22 VideoResolution.H_1080P,
26 for (const resolution of resolutions) {
27 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
28 resolutionsEnabled.push(resolution)
32 return resolutionsEnabled
35 async function getVideoFileSize (path: string) {
36 const videoStream = await getVideoStreamFromFile(path)
38 return videoStream == null
44 width: videoStream.width,
45 height: videoStream.height
49 async function getVideoFileResolution (path: string) {
50 const size = await getVideoFileSize(path)
53 videoFileResolution: Math.min(size.height, size.width),
54 isPortraitMode: size.height > size.width
58 async function getVideoFileFPS (path: string) {
59 const videoStream = await getVideoStreamFromFile(path)
61 if (videoStream == null) {
65 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
66 const valuesText: string = videoStream[key]
67 if (!valuesText) continue
69 const [ frames, seconds ] = valuesText.split('/')
70 if (!frames || !seconds) continue
72 const result = parseInt(frames, 10) / parseInt(seconds, 10)
73 if (result > 0) return Math.round(result)
79 async function getVideoFileBitrate (path: string) {
80 return new Promise<number>((res, rej) => {
81 ffmpeg.ffprobe(path, (err, metadata) => {
82 if (err) return rej(err)
84 return res(metadata.format.bit_rate)
89 function getDurationFromVideoFile (path: string) {
90 return new Promise<number>((res, rej) => {
91 ffmpeg.ffprobe(path, (err, metadata) => {
92 if (err) return rej(err)
94 return res(Math.floor(metadata.format.duration))
99 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
100 const pendingImageName = 'pending-' + imageName
103 filename: pendingImageName,
108 const pendingImagePath = join(folder, pendingImageName)
111 await new Promise<string>((res, rej) => {
112 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
114 .on('end', () => res(imageName))
118 const destination = join(folder, imageName)
119 await processImage(pendingImagePath, destination, size)
121 logger.error('Cannot generate image from video %s.', fromPath, { err })
124 await remove(pendingImagePath)
126 logger.debug('Cannot remove pending image path after generation error.', { err })
131 type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio' | 'split-audio'
133 interface BaseTranscodeOptions {
134 type: TranscodeOptionsType
137 resolution: VideoResolution
138 isPortraitMode?: boolean
141 interface HLSTranscodeOptions extends BaseTranscodeOptions {
145 videoFilename: string
149 interface QuickTranscodeOptions extends BaseTranscodeOptions {
150 type: 'quick-transcode'
153 interface VideoTranscodeOptions extends BaseTranscodeOptions {
157 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
162 interface SplitAudioTranscodeOptions extends BaseTranscodeOptions {
166 type TranscodeOptions = HLSTranscodeOptions | VideoTranscodeOptions | MergeAudioTranscodeOptions | SplitAudioTranscodeOptions | QuickTranscodeOptions
168 function transcode (options: TranscodeOptions) {
169 return new Promise<void>(async (res, rej) => {
171 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
172 .output(options.outputPath)
174 if (options.type === 'quick-transcode') {
175 command = await buildQuickTranscodeCommand(command)
176 } else if (options.type === 'hls') {
177 command = await buildHLSCommand(command, options)
178 } else if (options.type === 'merge-audio') {
179 command = await buildAudioMergeCommand(command, options)
180 } else if (options.type === 'split-audio') {
181 command = await buildAudioSplitCommand(command, options)
183 command = await buildx264Command(command, options)
186 if (CONFIG.TRANSCODING.THREADS > 0) {
187 // if we don't set any threads ffmpeg will chose automatically
188 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
192 .on('error', (err, stdout, stderr) => {
193 logger.error('Error in transcoding job.', { stdout, stderr })
197 return fixHLSPlaylistIfNeeded(options)
199 .catch(err => rej(err))
208 async function canDoQuickTranscode (path: string): Promise<boolean> {
209 // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
210 const videoStream = await getVideoStreamFromFile(path)
211 const parsedAudio = await audio.get(path)
212 const fps = await getVideoFileFPS(path)
213 const bitRate = await getVideoFileBitrate(path)
214 const resolution = await getVideoFileResolution(path)
216 // check video params
217 if (videoStream == null) return false
218 if (videoStream[ 'codec_name' ] !== 'h264') return false
219 if (videoStream[ 'pix_fmt' ] !== 'yuv420p') return false
220 if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
221 if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
223 // check audio params (if audio stream exists)
224 if (parsedAudio.audioStream) {
225 if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
227 const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
228 if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
234 // ---------------------------------------------------------------------------
238 getVideoFileResolution,
239 getDurationFromVideoFile,
240 generateImageFromVideoFile,
242 TranscodeOptionsType,
245 computeResolutionsToTranscode,
251 // ---------------------------------------------------------------------------
253 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
254 let fps = await getVideoFileFPS(options.inputPath)
255 // On small/medium resolutions, limit FPS
257 options.resolution !== undefined &&
258 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
259 fps > VIDEO_TRANSCODING_FPS.AVERAGE
261 fps = VIDEO_TRANSCODING_FPS.AVERAGE
264 command = await presetH264(command, options.inputPath, options.resolution, fps)
266 if (options.resolution !== undefined) {
267 // '?x720' or '720x?' for example
268 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
269 command = command.size(size)
274 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
275 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
277 command = command.withFPS(fps)
283 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
284 command = command.loop(undefined)
286 command = await presetH264VeryFast(command, options.audioPath, options.resolution)
288 command = command.input(options.audioPath)
289 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
290 .outputOption('-tune stillimage')
291 .outputOption('-shortest')
296 async function buildAudioSplitCommand (command: ffmpeg.FfmpegCommand, options: SplitAudioTranscodeOptions) {
297 command = await presetAudioSplit(command)
302 async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
303 command = await presetCopy(command)
305 command = command.outputOption('-map_metadata -1') // strip all metadata
306 .outputOption('-movflags faststart')
311 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
312 const videoPath = getHLSVideoPath(options)
314 if (options.copyCodecs) command = await presetCopy(command)
315 else command = await buildx264Command(command, options)
317 command = command.outputOption('-hls_time 4')
318 .outputOption('-hls_list_size 0')
319 .outputOption('-hls_playlist_type vod')
320 .outputOption('-hls_segment_filename ' + videoPath)
321 .outputOption('-hls_segment_type fmp4')
322 .outputOption('-f hls')
323 .outputOption('-hls_flags single_file')
328 function getHLSVideoPath (options: HLSTranscodeOptions) {
329 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
332 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
333 if (options.type !== 'hls') return
335 const fileContent = await readFile(options.outputPath)
337 const videoFileName = options.hlsPlaylist.videoFilename
338 const videoFilePath = getHLSVideoPath(options)
340 // Fix wrong mapping with some ffmpeg versions
341 const newContent = fileContent.toString()
342 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
344 await writeFile(options.outputPath, newContent)
347 function getVideoStreamFromFile (path: string) {
348 return new Promise<any>((res, rej) => {
349 ffmpeg.ffprobe(path, (err, metadata) => {
350 if (err) return rej(err)
352 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
353 //if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
355 return res(videoStream)
361 * A slightly customised version of the 'veryfast' x264 preset
363 * The veryfast preset is right in the sweet spot of performance
364 * and quality. Superfast and ultrafast will give you better
365 * performance, but then quality is noticeably worse.
367 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
368 let localCommand = await presetH264(command, input, resolution, fps)
370 localCommand = localCommand.outputOption('-preset:v veryfast')
373 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
374 Our target situation is closer to a livestream than a stream,
375 since we want to reduce as much a possible the encoding burden,
376 although not to the point of a livestream where there is a hard
377 constraint on the frames per second to be encoded.
384 * A toolbox to play with audio
387 export const get = (option: string) => {
388 // without position, ffprobe considers the last input only
389 // we make it consider the first input only
390 // if you pass a file path to pos, then ffprobe acts on that file directly
391 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
393 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
394 if (err) return rej(err)
396 if ('streams' in data) {
397 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
400 absolutePath: data.format.filename,
406 return res({ absolutePath: data.format.filename })
409 return ffmpeg.ffprobe(option, parseFfprobe)
413 export namespace bitrate {
414 const baseKbitrate = 384
416 const toBits = (kbits: number) => kbits * 8000
418 export const aac = (bitrate: number): number => {
420 case bitrate > toBits(baseKbitrate):
424 return -1 // we interpret it as a signal to copy the audio stream as is
428 export const mp3 = (bitrate: number): number => {
430 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
431 That's why, when using aac, we can go to lower kbit/sec. The equivalences
432 made here are not made to be accurate, especially with good mp3 encoders.
435 case bitrate <= toBits(192):
438 case bitrate <= toBits(384):
449 * Standard profile, with variable bitrate audio and faststart.
451 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
452 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
454 async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
455 let localCommand = command
457 .videoCodec('libx264')
458 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
459 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
460 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
461 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
462 .outputOption('-map_metadata -1') // strip all metadata
463 .outputOption('-movflags faststart')
465 const parsedAudio = await audio.get(input)
467 if (!parsedAudio.audioStream) {
468 localCommand = localCommand.noAudio()
469 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
470 localCommand = localCommand
471 .audioCodec('libfdk_aac')
474 // we try to reduce the ceiling bitrate by making rough matches of bitrates
475 // of course this is far from perfect, but it might save some space in the end
476 localCommand = localCommand.audioCodec('aac')
478 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
480 if (audio.bitrate[ audioCodecName ]) {
481 const bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
482 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
487 // Constrained Encoding (VBV)
488 // https://slhck.info/video/2017/03/01/rate-control.html
489 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
490 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
491 localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
493 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
494 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
495 // https://superuser.com/a/908325
496 localCommand = localCommand.outputOption(`-g ${fps * 2}`)
502 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {
510 async function presetAudioSplit (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {