ffmpeg-utils.ts 15 KB

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