1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { join } from 'path'
3 import { VideoResolution, getTargetBitrate } from '../../shared/models/videos'
4 import { CONFIG, FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers'
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 getVideoFileResolution (path: string) {
33 const videoStream = await getVideoFileStream(path)
36 videoFileResolution: Math.min(videoStream.height, videoStream.width),
37 isPortraitMode: videoStream.height > videoStream.width
41 async function getVideoFileFPS (path: string) {
42 const videoStream = await getVideoFileStream(path)
44 for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
45 const valuesText: string = videoStream[key]
46 if (!valuesText) continue
48 const [ frames, seconds ] = valuesText.split('/')
49 if (!frames || !seconds) continue
51 const result = parseInt(frames, 10) / parseInt(seconds, 10)
52 if (result > 0) return Math.round(result)
58 async function getVideoFileBitrate (path: string) {
59 return new Promise<number>((res, rej) => {
60 ffmpeg.ffprobe(path, (err, metadata) => {
61 if (err) return rej(err)
63 return res(metadata.format.bit_rate)
68 function getDurationFromVideoFile (path: string) {
69 return new Promise<number>((res, rej) => {
70 ffmpeg.ffprobe(path, (err, metadata) => {
71 if (err) return rej(err)
73 return res(Math.floor(metadata.format.duration))
78 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
79 const pendingImageName = 'pending-' + imageName
82 filename: pendingImageName,
87 const pendingImagePath = join(folder, pendingImageName)
90 await new Promise<string>((res, rej) => {
91 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
93 .on('end', () => res(imageName))
97 const destination = join(folder, imageName)
98 await processImage({ path: pendingImagePath }, destination, size)
100 logger.error('Cannot generate image from video %s.', fromPath, { err })
103 await remove(pendingImagePath)
105 logger.debug('Cannot remove pending image path after generation error.', { err })
110 type TranscodeOptions = {
113 resolution?: VideoResolution
114 isPortraitMode?: boolean
117 function transcode (options: TranscodeOptions) {
118 return new Promise<void>(async (res, rej) => {
119 let fps = await getVideoFileFPS(options.inputPath)
120 // On small/medium resolutions, limit FPS
122 // options.resolution !== undefined &&
123 // options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
124 // fps > VIDEO_TRANSCODING_FPS.AVERAGE
126 // fps = VIDEO_TRANSCODING_FPS.AVERAGE
129 let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
130 .output(options.outputPath)
131 command = await presetH264(command, options.resolution, fps)
133 if (CONFIG.TRANSCODING.THREADS > 0) {
134 // if we don't set any threads ffmpeg will chose automatically
135 command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
138 if (options.resolution !== undefined) {
139 // '?x720' or '720x?' for example
140 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
141 command = command.size(size)
146 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
147 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
149 command = command.withFPS(fps)
153 .on('error', (err, stdout, stderr) => {
154 logger.error('Error in transcoding job.', { stdout, stderr })
162 // ---------------------------------------------------------------------------
165 getVideoFileResolution,
166 getDurationFromVideoFile,
167 generateImageFromVideoFile,
170 computeResolutionsToTranscode,
175 // ---------------------------------------------------------------------------
177 function getVideoFileStream (path: string) {
178 return new Promise<any>((res, rej) => {
179 ffmpeg.ffprobe(path, (err, metadata) => {
180 if (err) return rej(err)
182 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
183 if (!videoStream) throw new Error('Cannot find video stream of ' + path)
185 return res(videoStream)
191 * A slightly customised version of the 'veryfast' x264 preset
193 * The veryfast preset is right in the sweet spot of performance
194 * and quality. Superfast and ultrafast will give you better
195 * performance, but then quality is noticeably worse.
197 async function presetH264VeryFast (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
198 const localFfmpeg = await presetH264(ffmpeg, resolution, fps)
200 .outputOption('-preset:v veryfast')
201 .outputOption(['--aq-mode=2', '--aq-strength=1.3'])
203 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
204 Our target situation is closer to a livestream than a stream,
205 since we want to reduce as much a possible the encoding burden,
206 altough not to the point of a livestream where there is a hard
207 constraint on the frames per second to be encoded.
209 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
210 Make up for most of the loss of grain and macroblocking
211 with less computing power.
216 * A preset optimised for a stillimage audio video
218 async function presetStillImageWithAudio (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
219 const localFfmpeg = await presetH264VeryFast(ffmpeg, resolution, fps)
221 .outputOption('-tune stillimage')
225 * A toolbox to play with audio
228 export const get = (_ffmpeg, pos: number | string = 0) => {
229 // without position, ffprobe considers the last input only
230 // we make it consider the first input only
231 // if you pass a file path to pos, then ffprobe acts on that file directly
232 return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
233 _ffmpeg.ffprobe(pos, (err,data) => {
234 if (err) return rej(err)
236 if ('streams' in data) {
237 const audioStream = data['streams'].find(stream => stream['codec_type'] === 'audio')
240 absolutePath: data.format.filename,
245 return res({ absolutePath: data.format.filename })
250 export namespace bitrate {
251 const baseKbitrate = 384
253 const toBits = (kbits: number): number => { return kbits * 8000 }
255 export const aac = (bitrate: number): number => {
257 case bitrate > toBits(baseKbitrate):
260 return -1 // we interpret it as a signal to copy the audio stream as is
264 export const mp3 = (bitrate: number): number => {
266 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
267 That's why, when using aac, we can go to lower kbit/sec. The equivalences
268 made here are not made to be accurate, especially with good mp3 encoders.
271 case bitrate <= toBits(192):
273 case bitrate <= toBits(384):
283 * Standard profile, with variable bitrate audio and faststart.
285 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
286 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
288 async function presetH264 (ffmpeg: ffmpeg, resolution: VideoResolution, fps: number): ffmpeg {
289 let localFfmpeg = ffmpeg
291 .videoCodec('libx264')
292 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
293 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
294 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
295 .outputOption('-map_metadata -1') // strip all metadata
296 .outputOption('-movflags faststart')
297 const _audio = await audio.get(localFfmpeg)
299 if (!_audio.audioStream) {
300 return localFfmpeg.noAudio()
303 // we favor VBR, if a good AAC encoder is available
304 if ((await checkFFmpegEncoders()).get('libfdk_aac')) {
306 .audioCodec('libfdk_aac')
310 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
311 // of course this is far from perfect, but it might save some space in the end
312 const audioCodecName = _audio.audioStream['codec_name']
314 if (audio.bitrate[audioCodecName]) {
315 bitrate = audio.bitrate[audioCodecName](_audio.audioStream['bit_rate'])
317 if (bitrate === -1) return localFfmpeg.audioCodec('copy')
320 if (bitrate !== undefined) return localFfmpeg.audioBitrate(bitrate)
322 // Constrained Encoding (VBV)
323 // https://slhck.info/video/2017/03/01/rate-control.html
324 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
325 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
326 localFfmpeg = localFfmpeg.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
328 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
329 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
330 // https://superuser.com/a/908325
331 localFfmpeg = localFfmpeg.outputOption(`-g ${ fps * 2 }`)