1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { join } from 'path'
3 import { VideoResolution } from '../../shared/models/videos'
4 import { CONFIG, VIDEO_TRANSCODING_FPS } from '../initializers'
5 import { unlinkPromise } from './core-utils'
6 import { processImage } from './image-utils'
7 import { logger } from './logger'
8 import { checkFFmpegEncoders } from '../initializers/checker'
10 async function getVideoFileResolution (path: string) {
11 const videoStream = await getVideoFileStream(path)
14 videoFileResolution: Math.min(videoStream.height, videoStream.width),
15 isPortraitMode: videoStream.height > videoStream.width
19 async function getVideoFileFPS (path: string) {
20 const videoStream = await getVideoFileStream(path)
22 for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
23 const valuesText: string = videoStream[key]
24 if (!valuesText) continue
26 const [ frames, seconds ] = valuesText.split('/')
27 if (!frames || !seconds) continue
29 const result = parseInt(frames, 10) / parseInt(seconds, 10)
30 if (result > 0) return Math.round(result)
36 function getDurationFromVideoFile (path: string) {
37 return new Promise<number>((res, rej) => {
38 ffmpeg.ffprobe(path, (err, metadata) => {
39 if (err) return rej(err)
41 return res(Math.floor(metadata.format.duration))
46 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
47 const pendingImageName = 'pending-' + imageName
50 filename: pendingImageName,
55 const pendingImagePath = join(folder, pendingImageName)
58 await new Promise<string>((res, rej) => {
61 .on('end', () => res(imageName))
65 const destination = join(folder, imageName)
66 await processImage({ path: pendingImagePath }, destination, size)
68 logger.error('Cannot generate image from video %s.', fromPath, { err })
71 await unlinkPromise(pendingImagePath)
73 logger.debug('Cannot remove pending image path after generation error.', { err })
78 type TranscodeOptions = {
81 resolution?: VideoResolution
82 isPortraitMode?: boolean
85 function transcode (options: TranscodeOptions) {
86 return new Promise<void>(async (res, rej) => {
87 let command = ffmpeg(options.inputPath)
88 .output(options.outputPath)
89 .outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
92 let fps = await getVideoFileFPS(options.inputPath)
93 if (options.resolution !== undefined) {
94 // '?x720' or '720x?' for example
95 const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
96 command = command.size(size)
98 // On small/medium resolutions, limit FPS
100 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
101 fps > VIDEO_TRANSCODING_FPS.AVERAGE
103 fps = VIDEO_TRANSCODING_FPS.AVERAGE
109 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
110 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
112 command = command.withFPS(fps)
116 .on('error', (err, stdout, stderr) => {
117 logger.error('Error in transcoding job.', { stdout, stderr })
125 // ---------------------------------------------------------------------------
128 getVideoFileResolution,
129 getDurationFromVideoFile,
130 generateImageFromVideoFile,
135 // ---------------------------------------------------------------------------
137 function getVideoFileStream (path: string) {
138 return new Promise<any>((res, rej) => {
139 ffmpeg.ffprobe(path, (err, metadata) => {
140 if (err) return rej(err)
142 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
143 if (!videoStream) throw new Error('Cannot find video stream of ' + path)
145 return res(videoStream)
151 * A slightly customised version of the 'veryfast' x264 preset
153 * The veryfast preset is right in the sweet spot of performance
154 * and quality. Superfast and ultrafast will give you better
155 * performance, but then quality is noticeably worse.
157 function veryfast (ffmpeg) {
160 .outputOption('-preset:v veryfast')
161 .outputOption(['--aq-mode=2', '--aq-strength=1.3'])
163 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
164 Our target situation is closer to a livestream than a stream,
165 since we want to reduce as much a possible the encoding burden,
166 altough not to the point of a livestream where there is a hard
167 constraint on the frames per second to be encoded.
169 why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
170 Make up for most of the loss of grain and macroblocking
171 with less computing power.
176 * A preset optimised for a stillimage audio video
178 function audio (ffmpeg) {
181 .outputOption('-tune stillimage')
185 * A toolbox to play with audio
188 export const get = (ffmpeg, pos = 0) => {
189 // without position, ffprobe considers the last input only
190 // we make it consider the first input only
192 .ffprobe(pos, (_,data) => {
193 return data['streams'].find(stream => {
194 return stream['codec_type'] === 'audio'
199 export namespace bitrate {
200 export const baseKbitrate = 384
202 const toBits = (kbits: number): number => { return kbits * 8000 }
204 export const aac = (bitrate: number): number => {
206 case bitrate > toBits(384):
209 return -1 // we interpret it as a signal to copy the audio stream as is
213 export const mp3 = (bitrate: number): number => {
215 case bitrate <= toBits(192):
217 case bitrate <= toBits(384):
227 * Standard profile, with variable bitrate audio and faststart.
229 * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
230 * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
232 async function standard (ffmpeg) {
233 let _bitrate = audio.bitrate.baseKbitrate
236 .videoCodec('libx264')
237 .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
238 .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
239 .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
240 .outputOption('-movflags faststart')
241 let _audio = audio.get(_ffmpeg)
243 if (!_audio) return _ffmpeg.noAudio()
245 // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
246 // of course this is far from perfect, but it might save some space in the end
247 if (audio.bitrate[_audio['codec_name']]) {
248 _bitrate = audio.bitrate[_audio['codec_name']](_audio['bit_rate'])
249 if (_bitrate === -1) {
250 return _ffmpeg.audioCodec('copy')
254 // we favor VBR, if a good AAC encoder is available
255 if ((await checkFFmpegEncoders()).get('libfdk_aac')) {
257 .audioCodec('libfdk_aac')
261 return _ffmpeg.audioBitrate(_bitrate)