Merge branch 'release/v1.3.0' into develop
[oweals/peertube.git] / server / helpers / ffmpeg-utils.ts
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'
10
11 function computeResolutionsToTranscode (videoFileHeight: number) {
12   const resolutionsEnabled: number[] = []
13   const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
14
15   // Put in the order we want to proceed jobs
16   const resolutions = [
17     VideoResolution.H_480P,
18     VideoResolution.H_360P,
19     VideoResolution.H_720P,
20     VideoResolution.H_240P,
21     VideoResolution.H_1080P
22   ]
23
24   for (const resolution of resolutions) {
25     if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
26       resolutionsEnabled.push(resolution)
27     }
28   }
29
30   return resolutionsEnabled
31 }
32
33 async function getVideoFileSize (path: string) {
34   const videoStream = await getVideoStreamFromFile(path)
35
36   return {
37     width: videoStream.width,
38     height: videoStream.height
39   }
40 }
41
42 async function getVideoFileResolution (path: string) {
43   const size = await getVideoFileSize(path)
44
45   return {
46     videoFileResolution: Math.min(size.height, size.width),
47     isPortraitMode: size.height > size.width
48   }
49 }
50
51 async function getVideoFileFPS (path: string) {
52   const videoStream = await getVideoStreamFromFile(path)
53
54   for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
55     const valuesText: string = videoStream[key]
56     if (!valuesText) continue
57
58     const [ frames, seconds ] = valuesText.split('/')
59     if (!frames || !seconds) continue
60
61     const result = parseInt(frames, 10) / parseInt(seconds, 10)
62     if (result > 0) return Math.round(result)
63   }
64
65   return 0
66 }
67
68 async function getVideoFileBitrate (path: string) {
69   return new Promise<number>((res, rej) => {
70     ffmpeg.ffprobe(path, (err, metadata) => {
71       if (err) return rej(err)
72
73       return res(metadata.format.bit_rate)
74     })
75   })
76 }
77
78 function getDurationFromVideoFile (path: string) {
79   return new Promise<number>((res, rej) => {
80     ffmpeg.ffprobe(path, (err, metadata) => {
81       if (err) return rej(err)
82
83       return res(Math.floor(metadata.format.duration))
84     })
85   })
86 }
87
88 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
89   const pendingImageName = 'pending-' + imageName
90
91   const options = {
92     filename: pendingImageName,
93     count: 1,
94     folder
95   }
96
97   const pendingImagePath = join(folder, pendingImageName)
98
99   try {
100     await new Promise<string>((res, rej) => {
101       ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
102         .on('error', rej)
103         .on('end', () => res(imageName))
104         .thumbnail(options)
105     })
106
107     const destination = join(folder, imageName)
108     await processImage(pendingImagePath, destination, size)
109   } catch (err) {
110     logger.error('Cannot generate image from video %s.', fromPath, { err })
111
112     try {
113       await remove(pendingImagePath)
114     } catch (err) {
115       logger.debug('Cannot remove pending image path after generation error.', { err })
116     }
117   }
118 }
119
120 type TranscodeOptions = {
121   inputPath: string
122   outputPath: string
123   resolution: VideoResolution
124   isPortraitMode?: boolean
125   doQuickTranscode?: Boolean
126
127   hlsPlaylist?: {
128     videoFilename: string
129   }
130 }
131
132 function transcode (options: TranscodeOptions) {
133   return new Promise<void>(async (res, rej) => {
134     try {
135       let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING })
136         .output(options.outputPath)
137
138       if (options.doQuickTranscode) {
139         if (options.hlsPlaylist) {
140           throw(Error("Quick transcode and HLS can't be used at the same time"))
141         }
142
143         command
144           .format('mp4')
145           .addOption('-c:v copy')
146           .addOption('-c:a copy')
147           .outputOption('-map_metadata -1') // strip all metadata
148           .outputOption('-movflags faststart')
149       } else if (options.hlsPlaylist) {
150         command = await buildHLSCommand(command, options)
151       } else {
152         command = await buildx264Command(command, options)
153       }
154
155       if (CONFIG.TRANSCODING.THREADS > 0) {
156         // if we don't set any threads ffmpeg will chose automatically
157         command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
158       }
159
160       command
161         .on('error', (err, stdout, stderr) => {
162           logger.error('Error in transcoding job.', { stdout, stderr })
163           return rej(err)
164         })
165         .on('end', () => {
166           return onTranscodingSuccess(options)
167             .then(() => res())
168             .catch(err => rej(err))
169         })
170         .run()
171     } catch (err) {
172       return rej(err)
173     }
174   })
175 }
176
177 async function canDoQuickTranscode (path: string): Promise<boolean> {
178   // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway)
179   const videoStream = await getVideoStreamFromFile(path)
180   const parsedAudio = await audio.get(path)
181   const fps = await getVideoFileFPS(path)
182   const bitRate = await getVideoFileBitrate(path)
183   const resolution = await getVideoFileResolution(path)
184
185   // check video params
186   if (videoStream[ 'codec_name' ] !== 'h264') return false
187   if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false
188   if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false
189
190     // check audio params (if audio stream exists)
191   if (parsedAudio.audioStream) {
192     if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false
193
194     const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ])
195     if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false
196   }
197
198   return true
199 }
200
201 // ---------------------------------------------------------------------------
202
203 export {
204   getVideoFileSize,
205   getVideoFileResolution,
206   getDurationFromVideoFile,
207   generateImageFromVideoFile,
208   transcode,
209   getVideoFileFPS,
210   computeResolutionsToTranscode,
211   audio,
212   getVideoFileBitrate,
213   canDoQuickTranscode
214 }
215
216 // ---------------------------------------------------------------------------
217
218 async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
219   let fps = await getVideoFileFPS(options.inputPath)
220   // On small/medium resolutions, limit FPS
221   if (
222     options.resolution !== undefined &&
223     options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
224     fps > VIDEO_TRANSCODING_FPS.AVERAGE
225   ) {
226     fps = VIDEO_TRANSCODING_FPS.AVERAGE
227   }
228
229   command = await presetH264(command, options.resolution, fps)
230
231   if (options.resolution !== undefined) {
232     // '?x720' or '720x?' for example
233     const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
234     command = command.size(size)
235   }
236
237   if (fps) {
238     // Hard FPS limits
239     if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX
240     else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
241
242     command = command.withFPS(fps)
243   }
244
245   return command
246 }
247
248 async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
249   const videoPath = getHLSVideoPath(options)
250
251   command = await presetCopy(command)
252
253   command = command.outputOption('-hls_time 4')
254                    .outputOption('-hls_list_size 0')
255                    .outputOption('-hls_playlist_type vod')
256                    .outputOption('-hls_segment_filename ' + videoPath)
257                    .outputOption('-hls_segment_type fmp4')
258                    .outputOption('-f hls')
259                    .outputOption('-hls_flags single_file')
260
261   return command
262 }
263
264 function getHLSVideoPath (options: TranscodeOptions) {
265   return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
266 }
267
268 async function onTranscodingSuccess (options: TranscodeOptions) {
269   if (!options.hlsPlaylist) return
270
271   // Fix wrong mapping with some ffmpeg versions
272   const fileContent = await readFile(options.outputPath)
273
274   const videoFileName = options.hlsPlaylist.videoFilename
275   const videoFilePath = getHLSVideoPath(options)
276
277   const newContent = fileContent.toString()
278                                 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
279
280   await writeFile(options.outputPath, newContent)
281 }
282
283 function getVideoStreamFromFile (path: string) {
284   return new Promise<any>((res, rej) => {
285     ffmpeg.ffprobe(path, (err, metadata) => {
286       if (err) return rej(err)
287
288       const videoStream = metadata.streams.find(s => s.codec_type === 'video')
289       if (!videoStream) return rej(new Error('Cannot find video stream of ' + path))
290
291       return res(videoStream)
292     })
293   })
294 }
295
296 /**
297  * A slightly customised version of the 'veryfast' x264 preset
298  *
299  * The veryfast preset is right in the sweet spot of performance
300  * and quality. Superfast and ultrafast will give you better
301  * performance, but then quality is noticeably worse.
302  */
303 async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
304   let localCommand = await presetH264(command, resolution, fps)
305   localCommand = localCommand.outputOption('-preset:v veryfast')
306              .outputOption([ '--aq-mode=2', '--aq-strength=1.3' ])
307   /*
308   MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
309   Our target situation is closer to a livestream than a stream,
310   since we want to reduce as much a possible the encoding burden,
311   altough not to the point of a livestream where there is a hard
312   constraint on the frames per second to be encoded.
313
314   why '--aq-mode=2 --aq-strength=1.3' instead of '-profile:v main'?
315     Make up for most of the loss of grain and macroblocking
316     with less computing power.
317   */
318
319   return localCommand
320 }
321
322 /**
323  * A preset optimised for a stillimage audio video
324  */
325 async function presetStillImageWithAudio (
326   command: ffmpeg.FfmpegCommand,
327   resolution: VideoResolution,
328   fps: number
329 ): Promise<ffmpeg.FfmpegCommand> {
330   let localCommand = await presetH264VeryFast(command, resolution, fps)
331   localCommand = localCommand.outputOption('-tune stillimage')
332
333   return localCommand
334 }
335
336 /**
337  * A toolbox to play with audio
338  */
339 namespace audio {
340   export const get = (option: ffmpeg.FfmpegCommand | string) => {
341     // without position, ffprobe considers the last input only
342     // we make it consider the first input only
343     // if you pass a file path to pos, then ffprobe acts on that file directly
344     return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => {
345
346       function parseFfprobe (err: any, data: ffmpeg.FfprobeData) {
347         if (err) return rej(err)
348
349         if ('streams' in data) {
350           const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
351           if (audioStream) {
352             return res({
353               absolutePath: data.format.filename,
354               audioStream
355             })
356           }
357         }
358
359         return res({ absolutePath: data.format.filename })
360       }
361
362       if (typeof option === 'string') {
363         return ffmpeg.ffprobe(option, parseFfprobe)
364       }
365
366       return option.ffprobe(parseFfprobe)
367     })
368   }
369
370   export namespace bitrate {
371     const baseKbitrate = 384
372
373     const toBits = (kbits: number): number => { return kbits * 8000 }
374
375     export const aac = (bitrate: number): number => {
376       switch (true) {
377       case bitrate > toBits(baseKbitrate):
378         return baseKbitrate
379       default:
380         return -1 // we interpret it as a signal to copy the audio stream as is
381       }
382     }
383
384     export const mp3 = (bitrate: number): number => {
385       /*
386       a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
387       That's why, when using aac, we can go to lower kbit/sec. The equivalences
388       made here are not made to be accurate, especially with good mp3 encoders.
389       */
390       switch (true) {
391       case bitrate <= toBits(192):
392         return 128
393       case bitrate <= toBits(384):
394         return 256
395       default:
396         return baseKbitrate
397       }
398     }
399   }
400 }
401
402 /**
403  * Standard profile, with variable bitrate audio and faststart.
404  *
405  * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
406  * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
407  */
408 async function presetH264 (command: ffmpeg.FfmpegCommand, resolution: VideoResolution, fps: number): Promise<ffmpeg.FfmpegCommand> {
409   let localCommand = command
410     .format('mp4')
411     .videoCodec('libx264')
412     .outputOption('-level 3.1') // 3.1 is the minimal ressource allocation for our highest supported resolution
413     .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorythm, 16 is optimal B-frames for it
414     .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
415     .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
416     .outputOption('-map_metadata -1') // strip all metadata
417     .outputOption('-movflags faststart')
418
419   const parsedAudio = await audio.get(localCommand)
420
421   if (!parsedAudio.audioStream) {
422     localCommand = localCommand.noAudio()
423   } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
424     localCommand = localCommand
425       .audioCodec('libfdk_aac')
426       .audioQuality(5)
427   } else {
428     // we try to reduce the ceiling bitrate by making rough correspondances of bitrates
429     // of course this is far from perfect, but it might save some space in the end
430     const audioCodecName = parsedAudio.audioStream[ 'codec_name' ]
431     let bitrate: number
432     if (audio.bitrate[ audioCodecName ]) {
433       localCommand = localCommand.audioCodec('aac')
434
435       bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ])
436       if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
437     }
438   }
439
440   // Constrained Encoding (VBV)
441   // https://slhck.info/video/2017/03/01/rate-control.html
442   // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
443   const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
444   localCommand = localCommand.outputOptions([`-maxrate ${ targetBitrate }`, `-bufsize ${ targetBitrate * 2 }`])
445
446   // Keyframe interval of 2 seconds for faster seeking and resolution switching.
447   // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
448   // https://superuser.com/a/908325
449   localCommand = localCommand.outputOption(`-g ${ fps * 2 }`)
450
451   return localCommand
452 }
453
454 async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> {
455   return command
456     .format('mp4')
457     .videoCodec('copy')
458     .audioCodec('copy')
459 }