1 import { Job } from 'bull'
2 import ffmpeg, { FfmpegCommand, FilterSpecification, getAvailableEncoders } 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 { pick } from '@shared/core-utils'
10 EncoderOptionsBuilder,
11 EncoderOptionsBuilderParams,
14 } from '../../shared/models/videos'
15 import { CONFIG } from '../initializers/config'
16 import { execPromise, promisify0 } from './core-utils'
17 import { computeFPS, ffprobePromise, getAudioStream, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from './ffprobe-utils'
18 import { processImage } from './image-utils'
19 import { logger, loggerTagsFactory } from './logger'
21 const lTags = loggerTagsFactory('ffmpeg')
25 * Functions that run transcoding/muxing ffmpeg processes
26 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
30 // ---------------------------------------------------------------------------
32 // ---------------------------------------------------------------------------
34 type StreamType = 'audio' | 'video'
36 // ---------------------------------------------------------------------------
38 // ---------------------------------------------------------------------------
40 // Detect supported encoders by ffmpeg
41 let supportedEncoders: Map<string, boolean>
42 async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
43 if (supportedEncoders !== undefined) {
44 return supportedEncoders
47 const getAvailableEncodersPromise = promisify0(getAvailableEncoders)
48 const availableFFmpegEncoders = await getAvailableEncodersPromise()
50 const searchEncoders = new Set<string>()
51 for (const type of [ 'live', 'vod' ]) {
52 for (const streamType of [ 'audio', 'video' ]) {
53 for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
54 searchEncoders.add(encoder)
59 supportedEncoders = new Map<string, boolean>()
61 for (const searchEncoder of searchEncoders) {
62 supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
65 logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders, ...lTags() })
67 return supportedEncoders
70 function resetSupportedEncoders () {
71 supportedEncoders = undefined
74 // ---------------------------------------------------------------------------
76 // ---------------------------------------------------------------------------
78 function convertWebPToJPG (path: string, destination: string): Promise<void> {
79 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
82 return runCommand({ command, silent: true })
88 newSize: { width: number, height: number }
90 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
92 .size(`${newSize.width}x${newSize.height}`)
95 return runCommand({ command })
98 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
99 const pendingImageName = 'pending-' + imageName
102 filename: pendingImageName,
107 const pendingImagePath = join(folder, pendingImageName)
110 await new Promise<string>((res, rej) => {
111 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
113 .on('end', () => res(imageName))
117 const destination = join(folder, imageName)
118 await processImage(pendingImagePath, destination, size)
120 logger.error('Cannot generate image from video %s.', fromPath, { err, ...lTags() })
123 await remove(pendingImagePath)
125 logger.debug('Cannot remove pending image path after generation error.', { err, ...lTags() })
130 // ---------------------------------------------------------------------------
131 // Transcode meta function
132 // ---------------------------------------------------------------------------
134 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
136 interface BaseTranscodeOptions {
137 type: TranscodeOptionsType
142 availableEncoders: AvailableEncoders
147 isPortraitMode?: boolean
152 interface HLSTranscodeOptions extends BaseTranscodeOptions {
156 videoFilename: string
160 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
166 videoFilename: string
170 interface QuickTranscodeOptions extends BaseTranscodeOptions {
171 type: 'quick-transcode'
174 interface VideoTranscodeOptions extends BaseTranscodeOptions {
178 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
183 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
187 type TranscodeOptions =
189 | HLSFromTSTranscodeOptions
190 | VideoTranscodeOptions
191 | MergeAudioTranscodeOptions
192 | OnlyAudioTranscodeOptions
193 | QuickTranscodeOptions
196 [ type in TranscodeOptionsType ]: (c: FfmpegCommand, o?: TranscodeOptions) => Promise<FfmpegCommand> | FfmpegCommand
198 'quick-transcode': buildQuickTranscodeCommand,
199 'hls': buildHLSVODCommand,
200 'hls-from-ts': buildHLSVODFromTSCommand,
201 'merge-audio': buildAudioMergeCommand,
202 'only-audio': buildOnlyAudioCommand,
203 'video': buildx264VODCommand
206 async function transcode (options: TranscodeOptions) {
207 logger.debug('Will run transcode.', { options, ...lTags() })
209 let command = getFFmpeg(options.inputPath, 'vod')
210 .output(options.outputPath)
212 command = await builders[options.type](command, options)
214 await runCommand({ command, job: options.job })
216 await fixHLSPlaylistIfNeeded(options)
219 // ---------------------------------------------------------------------------
220 // Live muxing/transcoding functions
221 // ---------------------------------------------------------------------------
223 async function getLiveTranscodingCommand (options: {
227 masterPlaylistName: string
229 resolutions: number[]
236 availableEncoders: AvailableEncoders
239 const { inputUrl, outPath, resolutions, fps, bitrate, availableEncoders, profile, masterPlaylistName, ratio } = options
241 const command = getFFmpeg(inputUrl, 'live')
243 const varStreamMap: string[] = []
245 const complexFilter: FilterSpecification[] = [
249 options: resolutions.length,
250 outputs: resolutions.map(r => `vtemp${r}`)
254 command.outputOption('-sc_threshold 0')
256 addDefaultEncoderGlobalParams({ command })
258 for (let i = 0; i < resolutions.length; i++) {
259 const resolution = resolutions[i]
260 const resolutionFPS = computeFPS(fps, resolution)
262 const baseEncoderBuilderParams = {
268 inputBitrate: bitrate,
275 videoType: 'live' as 'live'
279 const streamType: StreamType = 'video'
280 const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
281 if (!builderResult) {
282 throw new Error('No available live video encoder found')
285 command.outputOption(`-map [vout${resolution}]`)
287 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
290 'Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile,
291 { builderResult, fps: resolutionFPS, resolution, ...lTags() }
294 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
295 applyEncoderOptions(command, builderResult.result)
298 inputs: `vtemp${resolution}`,
299 filter: getScaleFilter(builderResult.result),
300 options: `w=-2:h=${resolution}`,
301 outputs: `vout${resolution}`
306 const streamType: StreamType = 'audio'
307 const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
308 if (!builderResult) {
309 throw new Error('No available live audio encoder found')
312 command.outputOption('-map a:0')
314 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
317 'Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile,
318 { builderResult, fps: resolutionFPS, resolution, ...lTags() }
321 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
322 applyEncoderOptions(command, builderResult.result)
325 varStreamMap.push(`v:${i},a:${i}`)
328 command.complexFilter(complexFilter)
330 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
332 command.outputOption('-var_stream_map', varStreamMap.join(' '))
337 function getLiveMuxingCommand (inputUrl: string, outPath: string, masterPlaylistName: string) {
338 const command = getFFmpeg(inputUrl, 'live')
340 command.outputOption('-c:v copy')
341 command.outputOption('-c:a copy')
342 command.outputOption('-map 0:a?')
343 command.outputOption('-map 0:v?')
345 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
350 function buildStreamSuffix (base: string, streamNum?: number) {
351 if (streamNum !== undefined) {
352 return `${base}:${streamNum}`
358 // ---------------------------------------------------------------------------
360 // ---------------------------------------------------------------------------
362 function addDefaultEncoderGlobalParams (options: {
363 command: FfmpegCommand
365 const { command } = options
367 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
368 command.outputOption('-max_muxing_queue_size 1024')
369 // strip all metadata
370 .outputOption('-map_metadata -1')
371 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
372 .outputOption('-pix_fmt yuv420p')
375 function addDefaultEncoderParams (options: {
376 command: FfmpegCommand
377 encoder: 'libx264' | string
381 const { command, encoder, fps, streamNum } = options
383 if (encoder === 'libx264') {
384 // 3.1 is the minimal resource allocation for our highest supported resolution
385 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
388 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
389 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
390 // https://superuser.com/a/908325
391 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
396 function addDefaultLiveHLSParams (command: FfmpegCommand, outPath: string, masterPlaylistName: string) {
397 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
398 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
399 command.outputOption('-hls_flags delete_segments+independent_segments')
400 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
401 command.outputOption('-master_pl_name ' + masterPlaylistName)
402 command.outputOption(`-f hls`)
404 command.output(join(outPath, '%v.m3u8'))
407 // ---------------------------------------------------------------------------
408 // Transcode VOD command builders
409 // ---------------------------------------------------------------------------
411 async function buildx264VODCommand (command: FfmpegCommand, options: TranscodeOptions) {
412 let fps = await getVideoFileFPS(options.inputPath)
413 fps = computeFPS(fps, options.resolution)
415 let scaleFilterValue: string
417 if (options.resolution !== undefined) {
418 scaleFilterValue = options.isPortraitMode === true
419 ? `w=${options.resolution}:h=-2`
420 : `w=-2:h=${options.resolution}`
423 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
428 async function buildAudioMergeCommand (command: FfmpegCommand, options: MergeAudioTranscodeOptions) {
429 command = command.loop(undefined)
431 const scaleFilterValue = getScaleCleanerValue()
432 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
434 command.outputOption('-preset:v veryfast')
436 command = command.input(options.audioPath)
437 .outputOption('-tune stillimage')
438 .outputOption('-shortest')
443 function buildOnlyAudioCommand (command: FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
444 command = presetOnlyAudio(command)
449 function buildQuickTranscodeCommand (command: FfmpegCommand) {
450 command = presetCopy(command)
452 command = command.outputOption('-map_metadata -1') // strip all metadata
453 .outputOption('-movflags faststart')
458 function addCommonHLSVODCommandOptions (command: FfmpegCommand, outputPath: string) {
459 return command.outputOption('-hls_time 4')
460 .outputOption('-hls_list_size 0')
461 .outputOption('-hls_playlist_type vod')
462 .outputOption('-hls_segment_filename ' + outputPath)
463 .outputOption('-hls_segment_type fmp4')
464 .outputOption('-f hls')
465 .outputOption('-hls_flags single_file')
468 async function buildHLSVODCommand (command: FfmpegCommand, options: HLSTranscodeOptions) {
469 const videoPath = getHLSVideoPath(options)
471 if (options.copyCodecs) command = presetCopy(command)
472 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
473 else command = await buildx264VODCommand(command, options)
475 addCommonHLSVODCommandOptions(command, videoPath)
480 function buildHLSVODFromTSCommand (command: FfmpegCommand, options: HLSFromTSTranscodeOptions) {
481 const videoPath = getHLSVideoPath(options)
483 command.outputOption('-c copy')
486 // Required for example when copying an AAC stream from an MPEG-TS
487 // Since it's a bitstream filter, we don't need to reencode the audio
488 command.outputOption('-bsf:a aac_adtstoasc')
491 addCommonHLSVODCommandOptions(command, videoPath)
496 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
497 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
499 const fileContent = await readFile(options.outputPath)
501 const videoFileName = options.hlsPlaylist.videoFilename
502 const videoFilePath = getHLSVideoPath(options)
504 // Fix wrong mapping with some ffmpeg versions
505 const newContent = fileContent.toString()
506 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
508 await writeFile(options.outputPath, newContent)
511 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
512 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
515 // ---------------------------------------------------------------------------
516 // Transcoding presets
517 // ---------------------------------------------------------------------------
519 // Run encoder builder depending on available encoders
520 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
521 // If the default one does not exist, check the next encoder
522 async function getEncoderBuilderResult (options: EncoderOptionsBuilderParams & {
523 streamType: 'video' | 'audio'
526 availableEncoders: AvailableEncoders
529 videoType: 'vod' | 'live'
531 const { availableEncoders, profile, streamType, videoType } = options
533 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
534 const encoders = availableEncoders.available[videoType]
536 for (const encoder of encodersToTry) {
537 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
538 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder, lTags())
542 if (!encoders[encoder]) {
543 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder, lTags())
547 // An object containing available profiles for this encoder
548 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
549 let builder = builderProfiles[profile]
552 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder, lTags())
553 builder = builderProfiles.default
556 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder, lTags())
561 const result = await builder(pick(options, [ 'input', 'resolution', 'inputBitrate', 'fps', 'inputRatio', 'streamNum' ]))
566 // If we don't have output options, then copy the input stream
567 encoder: result.copy === true
576 async function presetVideo (options: {
577 command: FfmpegCommand
579 transcodeOptions: TranscodeOptions
581 scaleFilterValue?: string
583 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
585 let localCommand = command
587 .outputOption('-movflags faststart')
589 addDefaultEncoderGlobalParams({ command })
591 const probe = await ffprobePromise(input)
594 const parsedAudio = await getAudioStream(input, probe)
595 const bitrate = await getVideoFileBitrate(input, probe)
596 const { ratio } = await getVideoFileResolution(input, probe)
598 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
600 if (!parsedAudio.audioStream) {
601 localCommand = localCommand.noAudio()
602 streamsToProcess = [ 'video' ]
605 for (const streamType of streamsToProcess) {
606 const { profile, resolution, availableEncoders } = transcodeOptions
608 const builderResult = await getEncoderBuilderResult({
615 inputBitrate: bitrate,
617 videoType: 'vod' as 'vod'
620 if (!builderResult) {
621 throw new Error('No available encoder found for stream ' + streamType)
625 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
626 builderResult.encoder, streamType, input, profile,
627 { builderResult, resolution, fps, ...lTags() }
630 if (streamType === 'video') {
631 localCommand.videoCodec(builderResult.encoder)
633 if (scaleFilterValue) {
634 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
636 } else if (streamType === 'audio') {
637 localCommand.audioCodec(builderResult.encoder)
640 applyEncoderOptions(localCommand, builderResult.result)
641 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
647 function presetCopy (command: FfmpegCommand): FfmpegCommand {
654 function presetOnlyAudio (command: FfmpegCommand): FfmpegCommand {
661 function applyEncoderOptions (command: FfmpegCommand, options: EncoderOptions): FfmpegCommand {
663 .inputOptions(options.inputOptions ?? [])
664 .outputOptions(options.outputOptions ?? [])
667 function getScaleFilter (options: EncoderOptions): string {
668 if (options.scaleFilter) return options.scaleFilter.name
673 // ---------------------------------------------------------------------------
675 // ---------------------------------------------------------------------------
677 function getFFmpeg (input: string, type: 'live' | 'vod') {
678 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
679 const command = ffmpeg(input, {
680 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
681 cwd: CONFIG.STORAGE.TMP_DIR
684 const threads = type === 'live'
685 ? CONFIG.LIVE.TRANSCODING.THREADS
686 : CONFIG.TRANSCODING.THREADS
689 // If we don't set any threads ffmpeg will chose automatically
690 command.outputOption('-threads ' + threads)
696 function getFFmpegVersion () {
697 return new Promise<string>((res, rej) => {
698 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
699 if (err) return rej(err)
700 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
702 return execPromise(`${ffmpegPath} -version`)
704 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
705 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
707 // Fix ffmpeg version that does not include patch version (4.4 for example)
708 let version = parsed[1]
709 if (version.match(/^\d+\.\d+$/)) {
715 .catch(err => rej(err))
720 async function runCommand (options: {
721 command: FfmpegCommand
722 silent?: boolean // false
725 const { command, silent = false, job } = options
727 return new Promise<void>((res, rej) => {
728 let shellCommand: string
730 command.on('start', cmdline => { shellCommand = cmdline })
732 command.on('error', (err, stdout, stderr) => {
733 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr, shellCommand, ...lTags() })
738 command.on('end', (stdout, stderr) => {
739 logger.debug('FFmpeg command ended.', { stdout, stderr, shellCommand, ...lTags() })
745 command.on('progress', progress => {
746 if (!progress.percent) return
748 job.progress(Math.round(progress.percent))
749 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err, ...lTags() }))
757 // Avoid "height not divisible by 2" error
758 function getScaleCleanerValue () {
759 return 'trunc(iw/2)*2:trunc(ih/2)*2'
762 // ---------------------------------------------------------------------------
765 getLiveTranscodingCommand,
766 getLiveMuxingCommand,
770 generateImageFromVideoFile,
772 TranscodeOptionsType,
777 resetSupportedEncoders,