ffmpeg auto thread
[oweals/peertube.git] / server / helpers / ffmpeg-utils.ts
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, FFMPEG_NICE } 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'
9
10 async function getVideoFileResolution (path: string) {
11   const videoStream = await getVideoFileStream(path)
12
13   return {
14     videoFileResolution: Math.min(videoStream.height, videoStream.width),
15     isPortraitMode: videoStream.height > videoStream.width
16   }
17 }
18
19 async function getVideoFileFPS (path: string) {
20   const videoStream = await getVideoFileStream(path)
21
22   for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
23     const valuesText: string = videoStream[key]
24     if (!valuesText) continue
25
26     const [ frames, seconds ] = valuesText.split('/')
27     if (!frames || !seconds) continue
28
29     const result = parseInt(frames, 10) / parseInt(seconds, 10)
30     if (result > 0) return Math.round(result)
31   }
32
33   return 0
34 }
35
36 function getDurationFromVideoFile (path: string) {
37   return new Promise<number>((res, rej) => {
38     ffmpeg.ffprobe(path, (err, metadata) => {
39       if (err) return rej(err)
40
41       return res(Math.floor(metadata.format.duration))
42     })
43   })
44 }
45
46 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
47   const pendingImageName = 'pending-' + imageName
48
49   const options = {
50     filename: pendingImageName,
51     count: 1,
52     folder
53   }
54
55   const pendingImagePath = join(folder, pendingImageName)
56
57   try {
58     await new Promise<string>((res, rej) => {
59       ffmpeg(fromPath, { 'niceness': FFMPEG_NICE.THUMBNAIL })
60         .on('error', rej)
61         .on('end', () => res(imageName))
62         .thumbnail(options)
63     })
64
65     const destination = join(folder, imageName)
66     await processImage({ path: pendingImagePath }, destination, size)
67   } catch (err) {
68     logger.error('Cannot generate image from video %s.', fromPath, { err })
69
70     try {
71       await unlinkPromise(pendingImagePath)
72     } catch (err) {
73       logger.debug('Cannot remove pending image path after generation error.', { err })
74     }
75   }
76 }
77
78 type TranscodeOptions = {
79   inputPath: string
80   outputPath: string
81   resolution?: VideoResolution
82   isPortraitMode?: boolean
83 }
84
85 function transcode (options: TranscodeOptions) {
86   return new Promise<void>(async (res, rej) => {
87     let command = ffmpeg(options.inputPath, { 'niceness': FFMPEG_NICE.TRANSCODING })
88                     .output(options.outputPath)
89                     .preset(standard)
90     if (CONFIG.TRANSCODING.THREADS > 0) {
91       command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS) // if we don't set any threads ffmpeg will chose automatically
92     }
93
94     let fps = await getVideoFileFPS(options.inputPath)
95     if (options.resolution !== undefined) {
96       // '?x720' or '720x?' for example
97       const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
98       command = command.size(size)
99
100       // On small/medium resolutions, limit FPS
101       if (
102         options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
103         fps > VIDEO_TRANSCODING_FPS.AVERAGE
104       ) {
105         fps = VIDEO_TRANSCODING_FPS.AVERAGE
106       }
107     }
108
109     if (fps) {
110       // Hard FPS limits
111       if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
112       else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
113
114       command = command.withFPS(fps)
115     }
116
117     command
118       .on('error', (err, stdout, stderr) => {
119         logger.error('Error in transcoding job.', { stdout, stderr })
120         return rej(err)
121       })
122       .on('end', res)
123       .run()
124   })
125 }
126
127 // ---------------------------------------------------------------------------
128
129 export {
130   getVideoFileResolution,
131   getDurationFromVideoFile,
132   generateImageFromVideoFile,
133   transcode,
134   getVideoFileFPS
135 }
136
137 // ---------------------------------------------------------------------------
138
139 function getVideoFileStream (path: string) {
140   return new Promise<any>((res, rej) => {
141     ffmpeg.ffprobe(path, (err, metadata) => {
142       if (err) return rej(err)
143
144       const videoStream = metadata.streams.find(s => s.codec_type === 'video')
145       if (!videoStream) throw new Error('Cannot find video stream of ' + path)
146
147       return res(videoStream)
148     })
149   })
150 }
151
152 /**
153  * A slightly customised version of the 'veryfast' x264 preset
154  *
155  * The veryfast preset is right in the sweet spot of performance
156  * and quality. Superfast and ultrafast will give you better
157  * performance, but then quality is noticeably worse.
158  */
159 function veryfast (_ffmpeg) {
160   _ffmpeg
161     .preset(standard)
162     .outputOption('-preset:v veryfast')
163     .outputOption(['--aq-mode=2', '--aq-strength=1.3'])
164   /*
165   MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
166   Our target situation is closer to a livestream than a stream,
167   since we want to reduce as much a possible the encoding burden,
168   altough not to the point of a livestream where there is a hard
169   constraint on the frames per second to be encoded.
170
171   why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
172     Make up for most of the loss of grain and macroblocking
173     with less computing power.
174   */
175 }
176
177 /**
178  * A preset optimised for a stillimage audio video
179  */
180 function audio (_ffmpeg) {
181   _ffmpeg
182     .preset(veryfast)
183     .outputOption('-tune stillimage')
184 }
185
186 /**
187  * A toolbox to play with audio
188  */
189 namespace audio {
190   export const get = (_ffmpeg, pos: number | string = 0) => {
191     // without position, ffprobe considers the last input only
192     // we make it consider the first input only
193     // if you pass a file path to pos, then ffprobe acts on that file directly
194     return new Promise<any>((res, rej) => {
195       _ffmpeg
196         .ffprobe(pos, (err,data) => {
197           if (err) return rej(err)
198
199           if ('streams' in data) {
200             return res(data['streams'].find(stream => stream['codec_type'] === 'audio'))
201           } else {
202             rej()
203           }
204         })
205     })
206   }
207
208   export namespace bitrate {
209     export const baseKbitrate = 384
210
211     const toBits = (kbits: number): number => { return kbits * 8000 }
212
213     export const aac = (bitrate: number): number => {
214       switch (true) {
215       case bitrate > toBits(384):
216         return baseKbitrate
217       default:
218         return -1 // we interpret it as a signal to copy the audio stream as is
219       }
220     }
221
222     export const mp3 = (bitrate: number): number => {
223       switch (true) {
224       case bitrate <= toBits(192):
225         return 128
226       case bitrate <= toBits(384):
227         return 256
228       default:
229         return baseKbitrate
230       }
231     }
232   }
233 }
234
235 /**
236  * Standard profile, with variable bitrate audio and faststart.
237  *
238  * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
239  * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
240  */
241 async function standard (_ffmpeg) {
242   let _bitrate = audio.bitrate.baseKbitrate
243   let localFfmpeg = _ffmpeg
244     .format('mp4')
245     .videoCodec('libx264')
246     .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
247     .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
248     .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
249     .outputOption('-map_metadata -1') // strip all metadata
250     .outputOption('-movflags faststart')
251   let _audio = audio.get(localFfmpeg)
252                     .then(res => res)
253                     .catch(_ => undefined)
254
255   if (!_audio) return localFfmpeg.noAudio()
256
257   // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
258   // of course this is far from perfect, but it might save some space in the end
259   if (audio.bitrate[_audio['codec_name']]) {
260     _bitrate = audio.bitrate[_audio['codec_name']](_audio['bit_rate'])
261     if (_bitrate === -1) {
262       return localFfmpeg.audioCodec('copy')
263     }
264   }
265
266   // we favor VBR, if a good AAC encoder is available
267   if ((await checkFFmpegEncoders()).get('libfdk_aac')) {
268     return localFfmpeg
269       .audioCodec('libfdk_aac')
270       .audioQuality(5)
271   }
272
273   return localFfmpeg.audioBitrate(_bitrate)
274 }