1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { dirname, join } from 'path'
3 import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
4 import { CONFIG, 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 { remove } from 'fs-extra'
10 function computeResolutionsToTranscode (videoFileHeight: number) {
11 const resolutionsEnabled: number[] = []
12 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
14 // Put in the order we want to proceed jobs
16 VideoResolution.H_480P,
17 VideoResolution.H_360P,
18 VideoResolution.H_720P,
19 VideoResolution.H_240P,
20 VideoResolution.H_1080P
23 for (const resolution of resolutions) {
24 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
25 resolutionsEnabled.push(resolution)
29 return resolutionsEnabled
32 async function getVideoFileSize (path: string) {
33 const videoStream = await getVideoFileStream(path)
36 width: videoStream.width,
37 height: videoStream.height
41 async function getVideoFileResolution (path: string) {
42 const size = await getVideoFileSize(path)
45 videoFileResolution: Math.min(size.height, size.width),
46 isPortraitMode: size.height > size.width
50 async function getVideoFileFPS (path: string) {
51 const videoStream = await getVideoFileStream(path)
53 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
54 const valuesText: string = videoStream[key]
55 if (!valuesText) continue
57 const [ frames, seconds ] = valuesText.split('/')
58 if (!frames || !seconds) continue
60 const result = parseInt(frames, 10) / parseInt(seconds, 10)
61 if (result > 0) return Math.round(result)
67 async function getVideoFileBitrate (path: string) {
68 return new Promise<number>((res, rej) => {
69 ffmpeg.ffprobe(path, (err, metadata) => {
70 if (err) return rej(err)
72 return res(metadata.format.bit_rate)
77 function getDurationFromVideoFile (path: string) {
78 return new Promise<number>((res, rej) => {
79 ffmpeg.ffprobe(path, (err, metadata) => {
80 if (err) return rej(err)
82 return res(Math.floor(metadata.format.duration))
87 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
88 const pendingImageName = 'pending-' + imageName
91 filename: pendingImageName,
96 const pendingImagePath = join(folder, pendingImageName)
99 await new Promise<string>((res, rej) => {
100 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
102 .on('end', () => res(imageName))
106 const destination = join(folder, imageName)
107 await processImage({ path: pendingImagePath }, destination, size)
109 logger.error('Cannot generate image from video %s.', fromPath, { err })
112 await remove(pendingImagePath)
114 logger.debug('Cannot remove pending image path after generation error.', { err })
119 type TranscodeOptions = {
122 resolution: VideoResolution
123 isPortraitMode?: boolean
125 generateHlsPlaylist?: boolean
128 function transcode (options: TranscodeOptions) {
129 return new Promise<void>(async (res, rej) => {
131 let fps = await getVideoFileFPS(options.inputPath)
132 // On small/medium resolutions, limit FPS
134 options.resolution !== undefined &&
135 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
136 fps > VIDEO_TRANSCODING_FPS.AVERAGE
138 fps = VIDEO_TRANSCODING_FPS.AVERAGE
141 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
142 .output(options.outputPath)
143 command = await presetH264(command, options.resolution, fps)
145 if (CONFIG.TRANSCODING.THREADS > 0) {
146 // if we don't set any threads ffmpeg will chose automatically
147 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
150 if (options.resolution !== undefined) {
151 // '?x720' or '720x?' for example
152 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
153 command = command.size(size)
158 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
159 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
161 command = command.withFPS(fps)
164 if (options.generateHlsPlaylist) {
165 const segmentFilename = `${dirname(options.outputPath)}/${options.resolution}_%03d.ts`
167 command = command.outputOption('-hls_time 4')
168 .outputOption('-hls_list_size 0')
169 .outputOption('-hls_playlist_type vod')
170 .outputOption('-hls_segment_filename ' + segmentFilename)
171 .outputOption('-f hls')
175 .on('error', (err, stdout, stderr) => {
176 logger.error('Error in transcoding job.', { stdout, stderr })
187 // ---------------------------------------------------------------------------
191 getVideoFileResolution,
192 getDurationFromVideoFile,
193 generateImageFromVideoFile,
196 computeResolutionsToTranscode,
201 // ---------------------------------------------------------------------------
203 function getVideoFileStream (path: string) {
204 return new Promise<any>((res, rej) => {
205 ffmpeg.ffprobe(path, (err, metadata) => {
206 if (err) return rej(err)
208 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
209 if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
211 return res(videoStream)
217 * A slightly customised version of the 'veryfast' x264 preset
219 * The veryfast preset is right in the sweet spot of performance
220 * and quality. Superfast and ultrafast will give you better
221 * performance, but then quality is noticeably worse.
223 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
224 let localCommand = await presetH264(command, resolution, fps)
225 localCommand = localCommand.outputOption('-preset:v veryfast')
226 .outputOption([ '--aq-mode=2', '--aq-strength=1.3' ])
228 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
229 Our target situation is closer to a livestream than a stream,
230 since we want to reduce as much a possible the encoding burden,
231 altough not to the point of a livestream where there is a hard
232 constraint on the frames per second to be encoded.
234 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
235 Make up for most of the loss of grain and macroblocking
236 with less computing power.
243 * A preset optimised for a stillimage audio video
245 async function presetStillImageWithAudio (
246 command: ffmpeg.FfmpegCommand,
247 resolution: VideoResolution,
249 ): Promise<ffmpeg.FfmpegCommand> {
250 let localCommand = await presetH264VeryFast(command, resolution, fps)
251 localCommand = localCommand.outputOption('-tune stillimage')
257 * A toolbox to play with audio
260 export const get = (option: ffmpeg.FfmpegCommand | string) => {
261 // without position, ffprobe considers the last input only
262 // we make it consider the first input only
263 // if you pass a file path to pos, then ffprobe acts on that file directly
264 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
266 function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
267 if (err) return rej(err)
269 if ('streams' in data) {
270 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
273 absolutePath: data.format.filename,
279 return res({ absolutePath: data.format.filename })
282 if (typeof option === 'string') {
283 return ffmpeg.ffprobe(option, parseFfprobe)
286 return option.ffprobe(parseFfprobe)
290 export namespace bitrate {
291 const baseKbitrate = 384
293 const toBits = (kbits: number): number => { return kbits * 8000 }
295 export const aac = (bitrate: number): number => {
297 case bitrate > toBits(baseKbitrate):
300 return -1 // we interpret it as a signal to copy the audio stream as is
304 export const mp3 = (bitrate: number): number => {
306 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
307 That's why, when using aac, we can go to lower kbit/sec. The equivalences
308 made here are not made to be accurate, especially with good mp3 encoders.
311 case bitrate <= toBits(192):
313 case bitrate <= toBits(384):
323 * Standard profile, with variable bitrate audio and faststart.
325 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
326 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
328 async function presetH264 (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
329 let localCommand = command
331 .videoCodec('libx264')
332 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
333 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
334 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
335 .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
336 .outputOption('-map_metadata -1') // strip all metadata
337 .outputOption('-movflags faststart')
339 const parsedAudio = await audio.get(localCommand)
341 if (!parsedAudio.audioStream) {
342 localCommand = localCommand.noAudio()
343 } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
344 localCommand = localCommand
345 .audioCodec('libfdk_aac')
348 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
349 // of course this is far from perfect, but it might save some space in the end
350 const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
352 if (audio.bitrate[ audioCodecName ]) {
353 localCommand = localCommand.audioCodec('aac')
355 bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
356 if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
360 // Constrained Encoding (VBV)
361 // https://slhck.info/video/2017/03/01/rate-control.html
362 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
363 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
364 localCommand = localCommand.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
366 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
367 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
368 // https://superuser.com/a/908325
369 localCommand = localCommand.outputOption(`-g ${ fps * 2 }`)