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 { 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 } from './logger'
23 * Functions that run transcoding/muxing ffmpeg processes
24 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
28 // ---------------------------------------------------------------------------
30 // ---------------------------------------------------------------------------
32 type StreamType = 'audio' | 'video'
34 // ---------------------------------------------------------------------------
36 // ---------------------------------------------------------------------------
38 // Detect supported encoders by ffmpeg
39 let supportedEncoders: Map<string, boolean>
40 async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
41 if (supportedEncoders !== undefined) {
42 return supportedEncoders
45 const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
46 const availableFFmpegEncoders = await getAvailableEncodersPromise()
48 const searchEncoders = new Set<string>()
49 for (const type of [ 'live', 'vod' ]) {
50 for (const streamType of [ 'audio', 'video' ]) {
51 for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
52 searchEncoders.add(encoder)
57 supportedEncoders = new Map<string, boolean>()
59 for (const searchEncoder of searchEncoders) {
60 supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
63 logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
65 return supportedEncoders
68 function resetSupportedEncoders () {
69 supportedEncoders = undefined
72 // ---------------------------------------------------------------------------
74 // ---------------------------------------------------------------------------
76 function convertWebPToJPG (path: string, destination: string): Promise<void> {
77 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
80 return runCommand({ command, silent: true })
86 newSize: { width: number, height: number }
88 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
90 .size(`${newSize.width}x${newSize.height}`)
93 return runCommand({ command })
96 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
97 const pendingImageName = 'pending-' + imageName
100 filename: pendingImageName,
105 const pendingImagePath = join(folder, pendingImageName)
108 await new Promise<string>((res, rej) => {
109 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
111 .on('end', () => res(imageName))
115 const destination = join(folder, imageName)
116 await processImage(pendingImagePath, destination, size)
118 logger.error('Cannot generate image from video %s.', fromPath, { err })
121 await remove(pendingImagePath)
123 logger.debug('Cannot remove pending image path after generation error.', { err })
128 // ---------------------------------------------------------------------------
129 // Transcode meta function
130 // ---------------------------------------------------------------------------
132 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
134 interface BaseTranscodeOptions {
135 type: TranscodeOptionsType
140 availableEncoders: AvailableEncoders
145 isPortraitMode?: boolean
150 interface HLSTranscodeOptions extends BaseTranscodeOptions {
154 videoFilename: string
158 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
164 videoFilename: string
168 interface QuickTranscodeOptions extends BaseTranscodeOptions {
169 type: 'quick-transcode'
172 interface VideoTranscodeOptions extends BaseTranscodeOptions {
176 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
181 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
185 type TranscodeOptions =
187 | HLSFromTSTranscodeOptions
188 | VideoTranscodeOptions
189 | MergeAudioTranscodeOptions
190 | OnlyAudioTranscodeOptions
191 | QuickTranscodeOptions
194 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
196 'quick-transcode': buildQuickTranscodeCommand,
197 'hls': buildHLSVODCommand,
198 'hls-from-ts': buildHLSVODFromTSCommand,
199 'merge-audio': buildAudioMergeCommand,
200 'only-audio': buildOnlyAudioCommand,
201 'video': buildx264VODCommand
204 async function transcode (options: TranscodeOptions) {
205 logger.debug('Will run transcode.', { options })
207 let command = getFFmpeg(options.inputPath, 'vod')
208 .output(options.outputPath)
210 command = await builders[options.type](command, options)
212 await runCommand({ command, job: options.job })
214 await fixHLSPlaylistIfNeeded(options)
217 // ---------------------------------------------------------------------------
218 // Live muxing/transcoding functions
219 // ---------------------------------------------------------------------------
221 async function getLiveTranscodingCommand (options: {
225 masterPlaylistName: string
227 resolutions: number[]
234 availableEncoders: AvailableEncoders
237 const { rtmpUrl, outPath, resolutions, fps, bitrate, availableEncoders, profile, masterPlaylistName, ratio } = options
238 const input = rtmpUrl
240 const command = getFFmpeg(input, 'live')
242 const varStreamMap: string[] = []
244 const complexFilter: ffmpeg.FilterSpecification[] = [
248 options: resolutions.length,
249 outputs: resolutions.map(r => `vtemp${r}`)
253 command.outputOption('-sc_threshold 0')
255 addDefaultEncoderGlobalParams({ command })
257 for (let i = 0; i < resolutions.length; i++) {
258 const resolution = resolutions[i]
259 const resolutionFPS = computeFPS(fps, resolution)
261 const baseEncoderBuilderParams = {
267 inputBitrate: bitrate,
274 videoType: 'live' as 'live'
278 const streamType: StreamType = 'video'
279 const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
280 if (!builderResult) {
281 throw new Error('No available live video encoder found')
284 command.outputOption(`-map [vout${resolution}]`)
286 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
288 logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
290 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
291 applyEncoderOptions(command, builderResult.result)
294 inputs: `vtemp${resolution}`,
295 filter: getScaleFilter(builderResult.result),
296 options: `w=-2:h=${resolution}`,
297 outputs: `vout${resolution}`
302 const streamType: StreamType = 'audio'
303 const builderResult = await getEncoderBuilderResult({ ...baseEncoderBuilderParams, streamType })
304 if (!builderResult) {
305 throw new Error('No available live audio encoder found')
308 command.outputOption('-map a:0')
310 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
312 logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
314 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
315 applyEncoderOptions(command, builderResult.result)
318 varStreamMap.push(`v:${i},a:${i}`)
321 command.complexFilter(complexFilter)
323 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
325 command.outputOption('-var_stream_map', varStreamMap.join(' '))
330 function getLiveMuxingCommand (rtmpUrl: string, outPath: string, masterPlaylistName: string) {
331 const command = getFFmpeg(rtmpUrl, 'live')
333 command.outputOption('-c:v copy')
334 command.outputOption('-c:a copy')
335 command.outputOption('-map 0:a?')
336 command.outputOption('-map 0:v?')
338 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
343 function buildStreamSuffix (base: string, streamNum?: number) {
344 if (streamNum !== undefined) {
345 return `${base}:${streamNum}`
351 // ---------------------------------------------------------------------------
353 // ---------------------------------------------------------------------------
355 function addDefaultEncoderGlobalParams (options: {
356 command: ffmpeg.FfmpegCommand
358 const { command } = options
360 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
361 command.outputOption('-max_muxing_queue_size 1024')
362 // strip all metadata
363 .outputOption('-map_metadata -1')
364 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
365 .outputOption('-b_strategy 1')
366 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
367 .outputOption('-bf 16')
368 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
369 .outputOption('-pix_fmt yuv420p')
372 function addDefaultEncoderParams (options: {
373 command: ffmpeg.FfmpegCommand
374 encoder: 'libx264' | string
378 const { command, encoder, fps, streamNum } = options
380 if (encoder === 'libx264') {
381 // 3.1 is the minimal resource allocation for our highest supported resolution
382 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
385 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
386 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
387 // https://superuser.com/a/908325
388 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
393 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, masterPlaylistName: string) {
394 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
395 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
396 command.outputOption('-hls_flags delete_segments+independent_segments')
397 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
398 command.outputOption('-master_pl_name ' + masterPlaylistName)
399 command.outputOption(`-f hls`)
401 command.output(join(outPath, '%v.m3u8'))
404 // ---------------------------------------------------------------------------
405 // Transcode VOD command builders
406 // ---------------------------------------------------------------------------
408 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
409 let fps = await getVideoFileFPS(options.inputPath)
410 fps = computeFPS(fps, options.resolution)
412 let scaleFilterValue: string
414 if (options.resolution !== undefined) {
415 scaleFilterValue = options.isPortraitMode === true
416 ? `w=${options.resolution}:h=-2`
417 : `w=-2:h=${options.resolution}`
420 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
425 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
426 command = command.loop(undefined)
428 const scaleFilterValue = getScaleCleanerValue()
429 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
431 command.outputOption('-preset:v veryfast')
433 command = command.input(options.audioPath)
434 .outputOption('-tune stillimage')
435 .outputOption('-shortest')
440 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
441 command = presetOnlyAudio(command)
446 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
447 command = presetCopy(command)
449 command = command.outputOption('-map_metadata -1') // strip all metadata
450 .outputOption('-movflags faststart')
455 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
456 return command.outputOption('-hls_time 4')
457 .outputOption('-hls_list_size 0')
458 .outputOption('-hls_playlist_type vod')
459 .outputOption('-hls_segment_filename ' + outputPath)
460 .outputOption('-hls_segment_type fmp4')
461 .outputOption('-f hls')
462 .outputOption('-hls_flags single_file')
465 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
466 const videoPath = getHLSVideoPath(options)
468 if (options.copyCodecs) command = presetCopy(command)
469 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
470 else command = await buildx264VODCommand(command, options)
472 addCommonHLSVODCommandOptions(command, videoPath)
477 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
478 const videoPath = getHLSVideoPath(options)
480 command.outputOption('-c copy')
483 // Required for example when copying an AAC stream from an MPEG-TS
484 // Since it's a bitstream filter, we don't need to reencode the audio
485 command.outputOption('-bsf:a aac_adtstoasc')
488 addCommonHLSVODCommandOptions(command, videoPath)
493 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
494 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
496 const fileContent = await readFile(options.outputPath)
498 const videoFileName = options.hlsPlaylist.videoFilename
499 const videoFilePath = getHLSVideoPath(options)
501 // Fix wrong mapping with some ffmpeg versions
502 const newContent = fileContent.toString()
503 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
505 await writeFile(options.outputPath, newContent)
508 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
509 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
512 // ---------------------------------------------------------------------------
513 // Transcoding presets
514 // ---------------------------------------------------------------------------
516 // Run encoder builder depending on available encoders
517 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
518 // If the default one does not exist, check the next encoder
519 async function getEncoderBuilderResult (options: EncoderOptionsBuilderParams & {
520 streamType: 'video' | 'audio'
523 availableEncoders: AvailableEncoders
526 videoType: 'vod' | 'live'
528 const { availableEncoders, profile, streamType, videoType } = options
530 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
531 const encoders = availableEncoders.available[videoType]
533 for (const encoder of encodersToTry) {
534 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
535 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
539 if (!encoders[encoder]) {
540 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
544 // An object containing available profiles for this encoder
545 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
546 let builder = builderProfiles[profile]
549 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
550 builder = builderProfiles.default
553 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
558 const result = await builder(pick(options, [ 'input', 'resolution', 'inputBitrate', 'fps', 'inputRatio', 'streamNum' ]))
563 // If we don't have output options, then copy the input stream
564 encoder: result.copy === true
573 async function presetVideo (options: {
574 command: ffmpeg.FfmpegCommand
576 transcodeOptions: TranscodeOptions
578 scaleFilterValue?: string
580 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
582 let localCommand = command
584 .outputOption('-movflags faststart')
586 addDefaultEncoderGlobalParams({ command })
588 const probe = await ffprobePromise(input)
591 const parsedAudio = await getAudioStream(input, probe)
592 const bitrate = await getVideoFileBitrate(input, probe)
593 const { ratio } = await getVideoFileResolution(input, probe)
595 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
597 if (!parsedAudio.audioStream) {
598 localCommand = localCommand.noAudio()
599 streamsToProcess = [ 'video' ]
602 for (const streamType of streamsToProcess) {
603 const { profile, resolution, availableEncoders } = transcodeOptions
605 const builderResult = await getEncoderBuilderResult({
612 inputBitrate: bitrate,
614 videoType: 'vod' as 'vod'
617 if (!builderResult) {
618 throw new Error('No available encoder found for stream ' + streamType)
622 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
623 builderResult.encoder, streamType, input, profile, builderResult
626 if (streamType === 'video') {
627 localCommand.videoCodec(builderResult.encoder)
629 if (scaleFilterValue) {
630 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
632 } else if (streamType === 'audio') {
633 localCommand.audioCodec(builderResult.encoder)
636 applyEncoderOptions(localCommand, builderResult.result)
637 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
643 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
650 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
657 function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
659 .inputOptions(options.inputOptions ?? [])
660 .outputOptions(options.outputOptions ?? [])
663 function getScaleFilter (options: EncoderOptions): string {
664 if (options.scaleFilter) return options.scaleFilter.name
669 // ---------------------------------------------------------------------------
671 // ---------------------------------------------------------------------------
673 function getFFmpeg (input: string, type: 'live' | 'vod') {
674 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
675 const command = ffmpeg(input, {
676 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
677 cwd: CONFIG.STORAGE.TMP_DIR
680 const threads = type === 'live'
681 ? CONFIG.LIVE.TRANSCODING.THREADS
682 : CONFIG.TRANSCODING.THREADS
685 // If we don't set any threads ffmpeg will chose automatically
686 command.outputOption('-threads ' + threads)
692 function getFFmpegVersion () {
693 return new Promise<string>((res, rej) => {
694 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
695 if (err) return rej(err)
696 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
698 return execPromise(`${ffmpegPath} -version`)
700 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
701 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
703 // Fix ffmpeg version that does not include patch version (4.4 for example)
704 let version = parsed[1]
705 if (version.match(/^\d+\.\d+$/)) {
711 .catch(err => rej(err))
716 async function runCommand (options: {
717 command: ffmpeg.FfmpegCommand
718 silent?: boolean // false
721 const { command, silent = false, job } = options
723 return new Promise<void>((res, rej) => {
724 let shellCommand: string
726 command.on('start', cmdline => { shellCommand = cmdline })
728 command.on('error', (err, stdout, stderr) => {
729 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })
734 command.on('end', (stdout, stderr) => {
735 logger.debug('FFmpeg command ended.', { stdout, stderr, shellCommand })
741 command.on('progress', progress => {
742 if (!progress.percent) return
744 job.progress(Math.round(progress.percent))
745 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
753 // Avoid "height not divisible by 2" error
754 function getScaleCleanerValue () {
755 return 'trunc(iw/2)*2:trunc(ih/2)*2'
758 // ---------------------------------------------------------------------------
761 getLiveTranscodingCommand,
762 getLiveMuxingCommand,
766 generateImageFromVideoFile,
768 TranscodeOptionsType,
773 resetSupportedEncoders,