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, builderResult,
291 { 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, builderResult,
318 { 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 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
372 .outputOption('-b_strategy 1')
373 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
374 .outputOption('-bf 16')
375 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
376 .outputOption('-pix_fmt yuv420p')
379 function addDefaultEncoderParams (options: {
380 command: FfmpegCommand
381 encoder: 'libx264' | string
385 const { command, encoder, fps, streamNum } = options
387 if (encoder === 'libx264') {
388 // 3.1 is the minimal resource allocation for our highest supported resolution
389 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
392 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
393 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
394 // https://superuser.com/a/908325
395 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
400 function addDefaultLiveHLSParams (command: FfmpegCommand, outPath: string, masterPlaylistName: string) {
401 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
402 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
403 command.outputOption('-hls_flags delete_segments+independent_segments')
404 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
405 command.outputOption('-master_pl_name ' + masterPlaylistName)
406 command.outputOption(`-f hls`)
408 command.output(join(outPath, '%v.m3u8'))
411 // ---------------------------------------------------------------------------
412 // Transcode VOD command builders
413 // ---------------------------------------------------------------------------
415 async function buildx264VODCommand (command: FfmpegCommand, options: TranscodeOptions) {
416 let fps = await getVideoFileFPS(options.inputPath)
417 fps = computeFPS(fps, options.resolution)
419 let scaleFilterValue: string
421 if (options.resolution !== undefined) {
422 scaleFilterValue = options.isPortraitMode === true
423 ? `w=${options.resolution}:h=-2`
424 : `w=-2:h=${options.resolution}`
427 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
432 async function buildAudioMergeCommand (command: FfmpegCommand, options: MergeAudioTranscodeOptions) {
433 command = command.loop(undefined)
435 const scaleFilterValue = getScaleCleanerValue()
436 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
438 command.outputOption('-preset:v veryfast')
440 command = command.input(options.audioPath)
441 .outputOption('-tune stillimage')
442 .outputOption('-shortest')
447 function buildOnlyAudioCommand (command: FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
448 command = presetOnlyAudio(command)
453 function buildQuickTranscodeCommand (command: FfmpegCommand) {
454 command = presetCopy(command)
456 command = command.outputOption('-map_metadata -1') // strip all metadata
457 .outputOption('-movflags faststart')
462 function addCommonHLSVODCommandOptions (command: FfmpegCommand, outputPath: string) {
463 return command.outputOption('-hls_time 4')
464 .outputOption('-hls_list_size 0')
465 .outputOption('-hls_playlist_type vod')
466 .outputOption('-hls_segment_filename ' + outputPath)
467 .outputOption('-hls_segment_type fmp4')
468 .outputOption('-f hls')
469 .outputOption('-hls_flags single_file')
472 async function buildHLSVODCommand (command: FfmpegCommand, options: HLSTranscodeOptions) {
473 const videoPath = getHLSVideoPath(options)
475 if (options.copyCodecs) command = presetCopy(command)
476 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
477 else command = await buildx264VODCommand(command, options)
479 addCommonHLSVODCommandOptions(command, videoPath)
484 function buildHLSVODFromTSCommand (command: FfmpegCommand, options: HLSFromTSTranscodeOptions) {
485 const videoPath = getHLSVideoPath(options)
487 command.outputOption('-c copy')
490 // Required for example when copying an AAC stream from an MPEG-TS
491 // Since it's a bitstream filter, we don't need to reencode the audio
492 command.outputOption('-bsf:a aac_adtstoasc')
495 addCommonHLSVODCommandOptions(command, videoPath)
500 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
501 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
503 const fileContent = await readFile(options.outputPath)
505 const videoFileName = options.hlsPlaylist.videoFilename
506 const videoFilePath = getHLSVideoPath(options)
508 // Fix wrong mapping with some ffmpeg versions
509 const newContent = fileContent.toString()
510 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
512 await writeFile(options.outputPath, newContent)
515 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
516 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
519 // ---------------------------------------------------------------------------
520 // Transcoding presets
521 // ---------------------------------------------------------------------------
523 // Run encoder builder depending on available encoders
524 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
525 // If the default one does not exist, check the next encoder
526 async function getEncoderBuilderResult (options: EncoderOptionsBuilderParams & {
527 streamType: 'video' | 'audio'
530 availableEncoders: AvailableEncoders
533 videoType: 'vod' | 'live'
535 const { availableEncoders, profile, streamType, videoType } = options
537 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
538 const encoders = availableEncoders.available[videoType]
540 for (const encoder of encodersToTry) {
541 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
542 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder, lTags())
546 if (!encoders[encoder]) {
547 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder, lTags())
551 // An object containing available profiles for this encoder
552 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
553 let builder = builderProfiles[profile]
556 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder, lTags())
557 builder = builderProfiles.default
560 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder, lTags())
565 const result = await builder(pick(options, [ 'input', 'resolution', 'inputBitrate', 'fps', 'inputRatio', 'streamNum' ]))
570 // If we don't have output options, then copy the input stream
571 encoder: result.copy === true
580 async function presetVideo (options: {
581 command: FfmpegCommand
583 transcodeOptions: TranscodeOptions
585 scaleFilterValue?: string
587 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
589 let localCommand = command
591 .outputOption('-movflags faststart')
593 addDefaultEncoderGlobalParams({ command })
595 const probe = await ffprobePromise(input)
598 const parsedAudio = await getAudioStream(input, probe)
599 const bitrate = await getVideoFileBitrate(input, probe)
600 const { ratio } = await getVideoFileResolution(input, probe)
602 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
604 if (!parsedAudio.audioStream) {
605 localCommand = localCommand.noAudio()
606 streamsToProcess = [ 'video' ]
609 for (const streamType of streamsToProcess) {
610 const { profile, resolution, availableEncoders } = transcodeOptions
612 const builderResult = await getEncoderBuilderResult({
619 inputBitrate: bitrate,
621 videoType: 'vod' as 'vod'
624 if (!builderResult) {
625 throw new Error('No available encoder found for stream ' + streamType)
629 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
630 builderResult.encoder, streamType, input, profile, builderResult,
631 { resolution, fps, ...lTags() }
634 if (streamType === 'video') {
635 localCommand.videoCodec(builderResult.encoder)
637 if (scaleFilterValue) {
638 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
640 } else if (streamType === 'audio') {
641 localCommand.audioCodec(builderResult.encoder)
644 applyEncoderOptions(localCommand, builderResult.result)
645 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
651 function presetCopy (command: FfmpegCommand): FfmpegCommand {
658 function presetOnlyAudio (command: FfmpegCommand): FfmpegCommand {
665 function applyEncoderOptions (command: FfmpegCommand, options: EncoderOptions): FfmpegCommand {
667 .inputOptions(options.inputOptions ?? [])
668 .outputOptions(options.outputOptions ?? [])
671 function getScaleFilter (options: EncoderOptions): string {
672 if (options.scaleFilter) return options.scaleFilter.name
677 // ---------------------------------------------------------------------------
679 // ---------------------------------------------------------------------------
681 function getFFmpeg (input: string, type: 'live' | 'vod') {
682 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
683 const command = ffmpeg(input, {
684 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
685 cwd: CONFIG.STORAGE.TMP_DIR
688 const threads = type === 'live'
689 ? CONFIG.LIVE.TRANSCODING.THREADS
690 : CONFIG.TRANSCODING.THREADS
693 // If we don't set any threads ffmpeg will chose automatically
694 command.outputOption('-threads ' + threads)
700 function getFFmpegVersion () {
701 return new Promise<string>((res, rej) => {
702 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
703 if (err) return rej(err)
704 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
706 return execPromise(`${ffmpegPath} -version`)
708 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
709 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
711 // Fix ffmpeg version that does not include patch version (4.4 for example)
712 let version = parsed[1]
713 if (version.match(/^\d+\.\d+$/)) {
719 .catch(err => rej(err))
724 async function runCommand (options: {
725 command: FfmpegCommand
726 silent?: boolean // false
729 const { command, silent = false, job } = options
731 return new Promise<void>((res, rej) => {
732 let shellCommand: string
734 command.on('start', cmdline => { shellCommand = cmdline })
736 command.on('error', (err, stdout, stderr) => {
737 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr, ...lTags() })
742 command.on('end', (stdout, stderr) => {
743 logger.debug('FFmpeg command ended.', { stdout, stderr, shellCommand, ...lTags() })
749 command.on('progress', progress => {
750 if (!progress.percent) return
752 job.progress(Math.round(progress.percent))
753 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err, ...lTags() }))
761 // Avoid "height not divisible by 2" error
762 function getScaleCleanerValue () {
763 return 'trunc(iw/2)*2:trunc(ih/2)*2'
766 // ---------------------------------------------------------------------------
769 getLiveTranscodingCommand,
770 getLiveMuxingCommand,
774 generateImageFromVideoFile,
776 TranscodeOptionsType,
781 resetSupportedEncoders,