ffmpeg-utils.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import { Job } from 'bull'
  2. import * as ffmpeg from 'fluent-ffmpeg'
  3. import { readFile, remove, writeFile } from 'fs-extra'
  4. import { dirname, join } from 'path'
  5. import { FFMPEG_NICE, VIDEO_LIVE } from '@server/initializers/constants'
  6. import { AvailableEncoders, EncoderOptions, EncoderOptionsBuilder, EncoderProfile, VideoResolution } from '../../shared/models/videos'
  7. import { CONFIG } from '../initializers/config'
  8. import { execPromise, promisify0 } from './core-utils'
  9. import { computeFPS, ffprobePromise, getAudioStream, getVideoFileBitrate, getVideoFileFPS } from './ffprobe-utils'
  10. import { processImage } from './image-utils'
  11. import { logger } from './logger'
  12. /**
  13. *
  14. * Functions that run transcoding/muxing ffmpeg processes
  15. * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
  16. *
  17. */
  18. // ---------------------------------------------------------------------------
  19. // Encoder options
  20. // ---------------------------------------------------------------------------
  21. type StreamType = 'audio' | 'video'
  22. // ---------------------------------------------------------------------------
  23. // Encoders support
  24. // ---------------------------------------------------------------------------
  25. // Detect supported encoders by ffmpeg
  26. let supportedEncoders: Map<string, boolean>
  27. async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
  28. if (supportedEncoders !== undefined) {
  29. return supportedEncoders
  30. }
  31. const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
  32. const availableFFmpegEncoders = await getAvailableEncodersPromise()
  33. const searchEncoders = new Set<string>()
  34. for (const type of [ 'live', 'vod' ]) {
  35. for (const streamType of [ 'audio', 'video' ]) {
  36. for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
  37. searchEncoders.add(encoder)
  38. }
  39. }
  40. }
  41. supportedEncoders = new Map<string, boolean>()
  42. for (const searchEncoder of searchEncoders) {
  43. supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
  44. }
  45. logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
  46. return supportedEncoders
  47. }
  48. function resetSupportedEncoders () {
  49. supportedEncoders = undefined
  50. }
  51. // ---------------------------------------------------------------------------
  52. // Image manipulation
  53. // ---------------------------------------------------------------------------
  54. function convertWebPToJPG (path: string, destination: string): Promise<void> {
  55. const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
  56. .output(destination)
  57. return runCommand({ command, silent: true })
  58. }
  59. function processGIF (
  60. path: string,
  61. destination: string,
  62. newSize: { width: number, height: number }
  63. ): Promise<void> {
  64. const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
  65. .fps(20)
  66. .size(`${newSize.width}x${newSize.height}`)
  67. .output(destination)
  68. return runCommand({ command })
  69. }
  70. async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
  71. const pendingImageName = 'pending-' + imageName
  72. const options = {
  73. filename: pendingImageName,
  74. count: 1,
  75. folder
  76. }
  77. const pendingImagePath = join(folder, pendingImageName)
  78. try {
  79. await new Promise<string>((res, rej) => {
  80. ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
  81. .on('error', rej)
  82. .on('end', () => res(imageName))
  83. .thumbnail(options)
  84. })
  85. const destination = join(folder, imageName)
  86. await processImage(pendingImagePath, destination, size)
  87. } catch (err) {
  88. logger.error('Cannot generate image from video %s.', fromPath, { err })
  89. try {
  90. await remove(pendingImagePath)
  91. } catch (err) {
  92. logger.debug('Cannot remove pending image path after generation error.', { err })
  93. }
  94. }
  95. }
  96. // ---------------------------------------------------------------------------
  97. // Transcode meta function
  98. // ---------------------------------------------------------------------------
  99. type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
  100. interface BaseTranscodeOptions {
  101. type: TranscodeOptionsType
  102. inputPath: string
  103. outputPath: string
  104. availableEncoders: AvailableEncoders
  105. profile: string
  106. resolution: number
  107. isPortraitMode?: boolean
  108. job?: Job
  109. }
  110. interface HLSTranscodeOptions extends BaseTranscodeOptions {
  111. type: 'hls'
  112. copyCodecs: boolean
  113. hlsPlaylist: {
  114. videoFilename: string
  115. }
  116. }
  117. interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
  118. type: 'hls-from-ts'
  119. isAAC: boolean
  120. hlsPlaylist: {
  121. videoFilename: string
  122. }
  123. }
  124. interface QuickTranscodeOptions extends BaseTranscodeOptions {
  125. type: 'quick-transcode'
  126. }
  127. interface VideoTranscodeOptions extends BaseTranscodeOptions {
  128. type: 'video'
  129. }
  130. interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
  131. type: 'merge-audio'
  132. audioPath: string
  133. }
  134. interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
  135. type: 'only-audio'
  136. }
  137. type TranscodeOptions =
  138. HLSTranscodeOptions
  139. | HLSFromTSTranscodeOptions
  140. | VideoTranscodeOptions
  141. | MergeAudioTranscodeOptions
  142. | OnlyAudioTranscodeOptions
  143. | QuickTranscodeOptions
  144. const builders: {
  145. [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
  146. } = {
  147. 'quick-transcode': buildQuickTranscodeCommand,
  148. 'hls': buildHLSVODCommand,
  149. 'hls-from-ts': buildHLSVODFromTSCommand,
  150. 'merge-audio': buildAudioMergeCommand,
  151. 'only-audio': buildOnlyAudioCommand,
  152. 'video': buildx264VODCommand
  153. }
  154. async function transcode (options: TranscodeOptions) {
  155. logger.debug('Will run transcode.', { options })
  156. let command = getFFmpeg(options.inputPath, 'vod')
  157. .output(options.outputPath)
  158. command = await builders[options.type](command, options)
  159. await runCommand({ command, job: options.job })
  160. await fixHLSPlaylistIfNeeded(options)
  161. }
  162. // ---------------------------------------------------------------------------
  163. // Live muxing/transcoding functions
  164. // ---------------------------------------------------------------------------
  165. async function getLiveTranscodingCommand (options: {
  166. rtmpUrl: string
  167. outPath: string
  168. masterPlaylistName: string
  169. resolutions: number[]
  170. fps: number
  171. bitrate: number
  172. availableEncoders: AvailableEncoders
  173. profile: string
  174. }) {
  175. const { rtmpUrl, outPath, resolutions, fps, bitrate, availableEncoders, profile, masterPlaylistName } = options
  176. const input = rtmpUrl
  177. const command = getFFmpeg(input, 'live')
  178. const varStreamMap: string[] = []
  179. const complexFilter: ffmpeg.FilterSpecification[] = [
  180. {
  181. inputs: '[v:0]',
  182. filter: 'split',
  183. options: resolutions.length,
  184. outputs: resolutions.map(r => `vtemp${r}`)
  185. }
  186. ]
  187. command.outputOption('-sc_threshold 0')
  188. addDefaultEncoderGlobalParams({ command })
  189. for (let i = 0; i < resolutions.length; i++) {
  190. const resolution = resolutions[i]
  191. const resolutionFPS = computeFPS(fps, resolution)
  192. const baseEncoderBuilderParams = {
  193. input,
  194. availableEncoders,
  195. profile,
  196. fps: resolutionFPS,
  197. inputBitrate: bitrate,
  198. resolution,
  199. streamNum: i,
  200. videoType: 'live' as 'live'
  201. }
  202. {
  203. const streamType: StreamType = 'video'
  204. const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
  205. if (!builderResult) {
  206. throw new Error('No available live video encoder found')
  207. }
  208. command.outputOption(`-map [vout${resolution}]`)
  209. addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
  210. logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
  211. command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
  212. applyEncoderOptions(command, builderResult.result)
  213. complexFilter.push({
  214. inputs: `vtemp${resolution}`,
  215. filter: getScaleFilter(builderResult.result),
  216. options: `w=-2:h=${resolution}`,
  217. outputs: `vout${resolution}`
  218. })
  219. }
  220. {
  221. const streamType: StreamType = 'audio'
  222. const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
  223. if (!builderResult) {
  224. throw new Error('No available live audio encoder found')
  225. }
  226. command.outputOption('-map a:0')
  227. addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
  228. logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
  229. command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
  230. applyEncoderOptions(command, builderResult.result)
  231. }
  232. varStreamMap.push(`v:${i},a:${i}`)
  233. }
  234. command.complexFilter(complexFilter)
  235. addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
  236. command.outputOption('-var_stream_map', varStreamMap.join(' '))
  237. return command
  238. }
  239. function getLiveMuxingCommand (rtmpUrl: string, outPath: string, masterPlaylistName: string) {
  240. const command = getFFmpeg(rtmpUrl, 'live')
  241. command.outputOption('-c:v copy')
  242. command.outputOption('-c:a copy')
  243. command.outputOption('-map 0:a?')
  244. command.outputOption('-map 0:v?')
  245. addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
  246. return command
  247. }
  248. function buildStreamSuffix (base: string, streamNum?: number) {
  249. if (streamNum !== undefined) {
  250. return `${base}:${streamNum}`
  251. }
  252. return base
  253. }
  254. // ---------------------------------------------------------------------------
  255. // Default options
  256. // ---------------------------------------------------------------------------
  257. function addDefaultEncoderGlobalParams (options: {
  258. command: ffmpeg.FfmpegCommand
  259. }) {
  260. const { command } = options
  261. // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
  262. command.outputOption('-max_muxing_queue_size 1024')
  263. // strip all metadata
  264. .outputOption('-map_metadata -1')
  265. // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
  266. .outputOption('-b_strategy 1')
  267. // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
  268. .outputOption('-bf 16')
  269. // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
  270. .outputOption('-pix_fmt yuv420p')
  271. }
  272. function addDefaultEncoderParams (options: {
  273. command: ffmpeg.FfmpegCommand
  274. encoder: 'libx264' | string
  275. streamNum?: number
  276. fps?: number
  277. }) {
  278. const { command, encoder, fps, streamNum } = options
  279. if (encoder === 'libx264') {
  280. // 3.1 is the minimal resource allocation for our highest supported resolution
  281. command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
  282. if (fps) {
  283. // Keyframe interval of 2 seconds for faster seeking and resolution switching.
  284. // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
  285. // https://superuser.com/a/908325
  286. command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
  287. }
  288. }
  289. }
  290. function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, masterPlaylistName: string) {
  291. command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
  292. command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
  293. command.outputOption('-hls_flags delete_segments+independent_segments')
  294. command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
  295. command.outputOption('-master_pl_name ' + masterPlaylistName)
  296. command.outputOption(`-f hls`)
  297. command.output(join(outPath, '%v.m3u8'))
  298. }
  299. // ---------------------------------------------------------------------------
  300. // Transcode VOD command builders
  301. // ---------------------------------------------------------------------------
  302. async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
  303. let fps = await getVideoFileFPS(options.inputPath)
  304. fps = computeFPS(fps, options.resolution)
  305. let scaleFilterValue: string
  306. if (options.resolution !== undefined) {
  307. scaleFilterValue = options.isPortraitMode === true
  308. ? `w=${options.resolution}:h=-2`
  309. : `w=-2:h=${options.resolution}`
  310. }
  311. command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
  312. return command
  313. }
  314. async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
  315. command = command.loop(undefined)
  316. const scaleFilterValue = getScaleCleanerValue()
  317. command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
  318. command.outputOption('-preset:v veryfast')
  319. command = command.input(options.audioPath)
  320. .outputOption('-tune stillimage')
  321. .outputOption('-shortest')
  322. return command
  323. }
  324. function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
  325. command = presetOnlyAudio(command)
  326. return command
  327. }
  328. function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
  329. command = presetCopy(command)
  330. command = command.outputOption('-map_metadata -1') // strip all metadata
  331. .outputOption('-movflags faststart')
  332. return command
  333. }
  334. function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
  335. return command.outputOption('-hls_time 4')
  336. .outputOption('-hls_list_size 0')
  337. .outputOption('-hls_playlist_type vod')
  338. .outputOption('-hls_segment_filename ' + outputPath)
  339. .outputOption('-hls_segment_type fmp4')
  340. .outputOption('-f hls')
  341. .outputOption('-hls_flags single_file')
  342. }
  343. async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
  344. const videoPath = getHLSVideoPath(options)
  345. if (options.copyCodecs) command = presetCopy(command)
  346. else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
  347. else command = await buildx264VODCommand(command, options)
  348. addCommonHLSVODCommandOptions(command, videoPath)
  349. return command
  350. }
  351. async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
  352. const videoPath = getHLSVideoPath(options)
  353. command.outputOption('-c copy')
  354. if (options.isAAC) {
  355. // Required for example when copying an AAC stream from an MPEG-TS
  356. // Since it's a bitstream filter, we don't need to reencode the audio
  357. command.outputOption('-bsf:a aac_adtstoasc')
  358. }
  359. addCommonHLSVODCommandOptions(command, videoPath)
  360. return command
  361. }
  362. async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
  363. if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
  364. const fileContent = await readFile(options.outputPath)
  365. const videoFileName = options.hlsPlaylist.videoFilename
  366. const videoFilePath = getHLSVideoPath(options)
  367. // Fix wrong mapping with some ffmpeg versions
  368. const newContent = fileContent.toString()
  369. .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
  370. await writeFile(options.outputPath, newContent)
  371. }
  372. function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
  373. return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
  374. }
  375. // ---------------------------------------------------------------------------
  376. // Transcoding presets
  377. // ---------------------------------------------------------------------------
  378. // Run encoder builder depending on available encoders
  379. // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
  380. // If the default one does not exist, check the next encoder
  381. async function getEncoderBuilderResult (options: {
  382. streamType: 'video' | 'audio'
  383. input: string
  384. availableEncoders: AvailableEncoders
  385. profile: string
  386. videoType: 'vod' | 'live'
  387. resolution: number
  388. inputBitrate: number
  389. fps?: number
  390. streamNum?: number
  391. }) {
  392. const { availableEncoders, input, profile, resolution, streamType, fps, inputBitrate, streamNum, videoType } = options
  393. const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
  394. const encoders = availableEncoders.available[videoType]
  395. for (const encoder of encodersToTry) {
  396. if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
  397. logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
  398. continue
  399. }
  400. if (!encoders[encoder]) {
  401. logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
  402. continue
  403. }
  404. // An object containing available profiles for this encoder
  405. const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
  406. let builder = builderProfiles[profile]
  407. if (!builder) {
  408. logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
  409. builder = builderProfiles.default
  410. if (!builder) {
  411. logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
  412. continue
  413. }
  414. }
  415. const result = await builder({ input, resolution, inputBitrate, fps, streamNum })
  416. return {
  417. result,
  418. // If we don't have output options, then copy the input stream
  419. encoder: result.copy === true
  420. ? 'copy'
  421. : encoder
  422. }
  423. }
  424. return null
  425. }
  426. async function presetVideo (options: {
  427. command: ffmpeg.FfmpegCommand
  428. input: string
  429. transcodeOptions: TranscodeOptions
  430. fps?: number
  431. scaleFilterValue?: string
  432. }) {
  433. const { command, input, transcodeOptions, fps, scaleFilterValue } = options
  434. let localCommand = command
  435. .format('mp4')
  436. .outputOption('-movflags faststart')
  437. addDefaultEncoderGlobalParams({ command })
  438. const probe = await ffprobePromise(input)
  439. // Audio encoder
  440. const parsedAudio = await getAudioStream(input, probe)
  441. const bitrate = await getVideoFileBitrate(input, probe)
  442. let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
  443. if (!parsedAudio.audioStream) {
  444. localCommand = localCommand.noAudio()
  445. streamsToProcess = [ 'video' ]
  446. }
  447. for (const streamType of streamsToProcess) {
  448. const { profile, resolution, availableEncoders } = transcodeOptions
  449. const builderResult = await getEncoderBuilderResult({
  450. streamType,
  451. input,
  452. resolution,
  453. availableEncoders,
  454. profile,
  455. fps,
  456. inputBitrate: bitrate,
  457. videoType: 'vod' as 'vod'
  458. })
  459. if (!builderResult) {
  460. throw new Error('No available encoder found for stream ' + streamType)
  461. }
  462. logger.debug(
  463. 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
  464. builderResult.encoder, streamType, input, profile, builderResult
  465. )
  466. if (streamType === 'video') {
  467. localCommand.videoCodec(builderResult.encoder)
  468. if (scaleFilterValue) {
  469. localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
  470. }
  471. } else if (streamType === 'audio') {
  472. localCommand.audioCodec(builderResult.encoder)
  473. }
  474. applyEncoderOptions(localCommand, builderResult.result)
  475. addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
  476. }
  477. return localCommand
  478. }
  479. function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
  480. return command
  481. .format('mp4')
  482. .videoCodec('copy')
  483. .audioCodec('copy')
  484. }
  485. function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
  486. return command
  487. .format('mp4')
  488. .audioCodec('copy')
  489. .noVideo()
  490. }
  491. function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
  492. return command
  493. .inputOptions(options.inputOptions ?? [])
  494. .outputOptions(options.outputOptions ?? [])
  495. }
  496. function getScaleFilter (options: EncoderOptions): string {
  497. if (options.scaleFilter) return options.scaleFilter.name
  498. return 'scale'
  499. }
  500. // ---------------------------------------------------------------------------
  501. // Utils
  502. // ---------------------------------------------------------------------------
  503. function getFFmpeg (input: string, type: 'live' | 'vod') {
  504. // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
  505. const command = ffmpeg(input, {
  506. niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
  507. cwd: CONFIG.STORAGE.TMP_DIR
  508. })
  509. const threads = type === 'live'
  510. ? CONFIG.LIVE.TRANSCODING.THREADS
  511. : CONFIG.TRANSCODING.THREADS
  512. if (threads > 0) {
  513. // If we don't set any threads ffmpeg will chose automatically
  514. command.outputOption('-threads ' + threads)
  515. }
  516. return command
  517. }
  518. function getFFmpegVersion () {
  519. return new Promise<string>((res, rej) => {
  520. (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
  521. if (err) return rej(err)
  522. if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
  523. return execPromise(`${ffmpegPath} -version`)
  524. .then(stdout => {
  525. const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
  526. if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
  527. // Fix ffmpeg version that does not include patch version (4.4 for example)
  528. let version = parsed[1]
  529. if (version.match(/^\d+\.\d+$/)) {
  530. version += '.0'
  531. }
  532. return res(version)
  533. })
  534. .catch(err => rej(err))
  535. })
  536. })
  537. }
  538. async function runCommand (options: {
  539. command: ffmpeg.FfmpegCommand
  540. silent?: boolean // false
  541. job?: Job
  542. }) {
  543. const { command, silent = false, job } = options
  544. return new Promise<void>((res, rej) => {
  545. let shellCommand: string
  546. command.on('start', cmdline => { shellCommand = cmdline })
  547. command.on('error', (err, stdout, stderr) => {
  548. if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })
  549. rej(err)
  550. })
  551. command.on('end', (stdout, stderr) => {
  552. logger.debug('FFmpeg command ended.', { stdout, stderr, shellCommand })
  553. res()
  554. })
  555. if (job) {
  556. command.on('progress', progress => {
  557. if (!progress.percent) return
  558. job.progress(Math.round(progress.percent))
  559. .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
  560. })
  561. }
  562. command.run()
  563. })
  564. }
  565. // Avoid "height not divisible by 2" error
  566. function getScaleCleanerValue () {
  567. return 'trunc(iw/2)*2:trunc(ih/2)*2'
  568. }
  569. // ---------------------------------------------------------------------------
  570. export {
  571. getLiveTranscodingCommand,
  572. getLiveMuxingCommand,
  573. buildStreamSuffix,
  574. convertWebPToJPG,
  575. processGIF,
  576. generateImageFromVideoFile,
  577. TranscodeOptions,
  578. TranscodeOptionsType,
  579. transcode,
  580. runCommand,
  581. getFFmpegVersion,
  582. resetSupportedEncoders,
  583. // builders
  584. buildx264VODCommand
  585. }