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, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
10 import { processImage } from './image-utils'
11 import { logger } from './logger'
15 * Functions that run transcoding/muxing ffmpeg processes
16 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
20 // ---------------------------------------------------------------------------
22 // ---------------------------------------------------------------------------
24 type StreamType = 'audio' | 'video'
26 // ---------------------------------------------------------------------------
28 // ---------------------------------------------------------------------------
30 // Detect supported encoders by ffmpeg
31 let supportedEncoders: Map<string, boolean>
32 async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
33 if (supportedEncoders !== undefined) {
34 return supportedEncoders
37 const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
38 const availableFFmpegEncoders = await getAvailableEncodersPromise()
40 const searchEncoders = new Set<string>()
41 for (const type of [ 'live', 'vod' ]) {
42 for (const streamType of [ 'audio', 'video' ]) {
43 for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
44 searchEncoders.add(encoder)
49 supportedEncoders = new Map<string, boolean>()
51 for (const searchEncoder of searchEncoders) {
52 supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
55 logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
57 return supportedEncoders
60 function resetSupportedEncoders () {
61 supportedEncoders = undefined
64 // ---------------------------------------------------------------------------
66 // ---------------------------------------------------------------------------
68 function convertWebPToJPG (path: string, destination: string): Promise<void> {
69 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
72 return runCommand({ command, silent: true })
78 newSize: { width: number, height: number }
80 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
82 .size(`${newSize.width}x${newSize.height}`)
85 return runCommand({ command })
88 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
89 const pendingImageName = 'pending-' + imageName
92 filename: pendingImageName,
97 const pendingImagePath = join(folder, pendingImageName)
100 await new Promise<string>((res, rej) => {
101 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
103 .on('end', () => res(imageName))
107 const destination = join(folder, imageName)
108 await processImage(pendingImagePath, destination, size)
110 logger.error('Cannot generate image from video %s.', fromPath, { err })
113 await remove(pendingImagePath)
115 logger.debug('Cannot remove pending image path after generation error.', { err })
120 // ---------------------------------------------------------------------------
121 // Transcode meta function
122 // ---------------------------------------------------------------------------
124 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
126 interface BaseTranscodeOptions {
127 type: TranscodeOptionsType
132 availableEncoders: AvailableEncoders
137 isPortraitMode?: boolean
142 interface HLSTranscodeOptions extends BaseTranscodeOptions {
146 videoFilename: string
150 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
156 videoFilename: string
160 interface QuickTranscodeOptions extends BaseTranscodeOptions {
161 type: 'quick-transcode'
164 interface VideoTranscodeOptions extends BaseTranscodeOptions {
168 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
173 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
177 type TranscodeOptions =
179 | HLSFromTSTranscodeOptions
180 | VideoTranscodeOptions
181 | MergeAudioTranscodeOptions
182 | OnlyAudioTranscodeOptions
183 | QuickTranscodeOptions
186 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
188 'quick-transcode': buildQuickTranscodeCommand,
189 'hls': buildHLSVODCommand,
190 'hls-from-ts': buildHLSVODFromTSCommand,
191 'merge-audio': buildAudioMergeCommand,
192 'only-audio': buildOnlyAudioCommand,
193 'video': buildx264VODCommand
196 async function transcode (options: TranscodeOptions) {
197 logger.debug('Will run transcode.', { options })
199 let command = getFFmpeg(options.inputPath, 'vod')
200 .output(options.outputPath)
202 command = await builders[options.type](command, options)
204 await runCommand({ command, job: options.job })
206 await fixHLSPlaylistIfNeeded(options)
209 // ---------------------------------------------------------------------------
210 // Live muxing/transcoding functions
211 // ---------------------------------------------------------------------------
213 async function getLiveTranscodingCommand (options: {
216 resolutions: number[]
219 availableEncoders: AvailableEncoders
222 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
223 const input = rtmpUrl
225 const command = getFFmpeg(input, 'live')
227 const varStreamMap: string[] = []
229 const complexFilter: FilterSpecification[] = [
233 options: resolutions.length,
234 outputs: resolutions.map(r => `vtemp${r}`)
238 command.outputOption('-sc_threshold 0')
240 addDefaultEncoderGlobalParams({ command })
242 for (let i = 0; i < resolutions.length; i++) {
243 const resolution = resolutions[i]
244 const resolutionFPS = computeFPS(fps, resolution)
246 const baseEncoderBuilderParams = {
255 videoType: 'live' as 'live'
259 const streamType: StreamType = 'video'
260 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
261 if (!builderResult) {
262 throw new Error('No available live video encoder found')
265 command.outputOption(`-map [vout${resolution}]`)
267 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
269 logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
271 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
272 applyEncoderOptions(command, builderResult.result)
275 inputs: `vtemp${resolution}`,
276 filter: getScaleFilter(builderResult.result),
277 options: `w=-2:h=${resolution}`,
278 outputs: `vout${resolution}`
283 const streamType: StreamType = 'audio'
284 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
285 if (!builderResult) {
286 throw new Error('No available live audio encoder found')
289 command.outputOption('-map a:0')
291 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
293 logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
295 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
296 applyEncoderOptions(command, builderResult.result)
299 varStreamMap.push(`v:${i},a:${i}`)
302 command.complexFilter(complexFilter)
304 addDefaultLiveHLSParams(command, outPath)
306 command.outputOption('-var_stream_map', varStreamMap.join(' '))
311 function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
312 const command = getFFmpeg(rtmpUrl, 'live')
314 command.outputOption('-c:v copy')
315 command.outputOption('-c:a copy')
316 command.outputOption('-map 0:a?')
317 command.outputOption('-map 0:v?')
319 addDefaultLiveHLSParams(command, outPath)
324 function buildStreamSuffix (base: string, streamNum?: number) {
325 if (streamNum !== undefined) {
326 return `${base}:${streamNum}`
332 // ---------------------------------------------------------------------------
334 // ---------------------------------------------------------------------------
336 function addDefaultEncoderGlobalParams (options: {
337 command: ffmpeg.FfmpegCommand
339 const { command } = options
341 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
342 command.outputOption('-max_muxing_queue_size 1024')
343 // strip all metadata
344 .outputOption('-map_metadata -1')
345 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
346 .outputOption('-b_strategy 1')
347 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
348 .outputOption('-bf 16')
349 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
350 .outputOption('-pix_fmt yuv420p')
353 function addDefaultEncoderParams (options: {
354 command: ffmpeg.FfmpegCommand
355 encoder: 'libx264' | string
359 const { command, encoder, fps, streamNum } = options
361 if (encoder === 'libx264') {
362 // 3.1 is the minimal resource allocation for our highest supported resolution
363 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
366 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
367 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
368 // https://superuser.com/a/908325
369 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
374 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
375 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
376 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
377 command.outputOption('-hls_flags delete_segments+independent_segments')
378 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
379 command.outputOption('-master_pl_name master.m3u8')
380 command.outputOption(`-f hls`)
382 command.output(join(outPath, '%v.m3u8'))
385 // ---------------------------------------------------------------------------
386 // Transcode VOD command builders
387 // ---------------------------------------------------------------------------
389 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
390 let fps = await getVideoFileFPS(options.inputPath)
391 fps = computeFPS(fps, options.resolution)
393 let scaleFilterValue: string
395 if (options.resolution !== undefined) {
396 scaleFilterValue = options.isPortraitMode === true
397 ? `w=${options.resolution}:h=-2`
398 : `w=-2:h=${options.resolution}`
401 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
406 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
407 command = command.loop(undefined)
409 const scaleFilterValue = getScaleCleanerValue()
410 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
412 command.outputOption('-preset:v veryfast')
414 command = command.input(options.audioPath)
415 .outputOption('-tune stillimage')
416 .outputOption('-shortest')
421 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
422 command = presetOnlyAudio(command)
427 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
428 command = presetCopy(command)
430 command = command.outputOption('-map_metadata -1') // strip all metadata
431 .outputOption('-movflags faststart')
436 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
437 return command.outputOption('-hls_time 4')
438 .outputOption('-hls_list_size 0')
439 .outputOption('-hls_playlist_type vod')
440 .outputOption('-hls_segment_filename ' + outputPath)
441 .outputOption('-hls_segment_type fmp4')
442 .outputOption('-f hls')
443 .outputOption('-hls_flags single_file')
446 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
447 const videoPath = getHLSVideoPath(options)
449 if (options.copyCodecs) command = presetCopy(command)
450 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
451 else command = await buildx264VODCommand(command, options)
453 addCommonHLSVODCommandOptions(command, videoPath)
458 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
459 const videoPath = getHLSVideoPath(options)
461 command.outputOption('-c copy')
464 // Required for example when copying an AAC stream from an MPEG-TS
465 // Since it's a bitstream filter, we don't need to reencode the audio
466 command.outputOption('-bsf:a aac_adtstoasc')
469 addCommonHLSVODCommandOptions(command, videoPath)
474 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
475 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
477 const fileContent = await readFile(options.outputPath)
479 const videoFileName = options.hlsPlaylist.videoFilename
480 const videoFilePath = getHLSVideoPath(options)
482 // Fix wrong mapping with some ffmpeg versions
483 const newContent = fileContent.toString()
484 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
486 await writeFile(options.outputPath, newContent)
489 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
490 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
493 // ---------------------------------------------------------------------------
494 // Transcoding presets
495 // ---------------------------------------------------------------------------
497 // Run encoder builder depending on available encoders
498 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
499 // If the default one does not exist, check the next encoder
500 async function getEncoderBuilderResult (options: {
501 streamType: 'video' | 'audio'
504 availableEncoders: AvailableEncoders
507 videoType: 'vod' | 'live'
513 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
515 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
516 const encoders = availableEncoders.available[videoType]
518 for (const encoder of encodersToTry) {
519 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
520 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
524 if (!encoders[encoder]) {
525 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
529 // An object containing available profiles for this encoder
530 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
531 let builder = builderProfiles[profile]
534 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
535 builder = builderProfiles.default
538 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
543 const result = await builder({ input, resolution, fps, streamNum })
548 // If we don't have output options, then copy the input stream
549 encoder: result.copy === true
558 async function presetVideo (options: {
559 command: ffmpeg.FfmpegCommand
561 transcodeOptions: TranscodeOptions
563 scaleFilterValue?: string
565 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
567 let localCommand = command
569 .outputOption('-movflags faststart')
571 addDefaultEncoderGlobalParams({ command })
574 const parsedAudio = await getAudioStream(input)
576 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
578 if (!parsedAudio.audioStream) {
579 localCommand = localCommand.noAudio()
580 streamsToProcess = [ 'video' ]
583 for (const streamType of streamsToProcess) {
584 const { profile, resolution, availableEncoders } = transcodeOptions
586 const builderResult = await getEncoderBuilderResult({
593 videoType: 'vod' as 'vod'
596 if (!builderResult) {
597 throw new Error('No available encoder found for stream ' + streamType)
601 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
602 builderResult.encoder, streamType, input, profile, builderResult
605 if (streamType === 'video') {
606 localCommand.videoCodec(builderResult.encoder)
608 if (scaleFilterValue) {
609 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
611 } else if (streamType === 'audio') {
612 localCommand.audioCodec(builderResult.encoder)
615 applyEncoderOptions(localCommand, builderResult.result)
616 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
622 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
629 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
636 function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
638 .inputOptions(options.inputOptions ?? [])
639 .outputOptions(options.outputOptions ?? [])
642 function getScaleFilter (options: EncoderOptions): string {
643 if (options.scaleFilter) return options.scaleFilter.name
648 // ---------------------------------------------------------------------------
650 // ---------------------------------------------------------------------------
652 function getFFmpeg (input: string, type: 'live' | 'vod') {
653 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
654 const command = ffmpeg(input, {
655 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
656 cwd: CONFIG.STORAGE.TMP_DIR
659 const threads = type === 'live'
660 ? CONFIG.LIVE.TRANSCODING.THREADS
661 : CONFIG.TRANSCODING.THREADS
664 // If we don't set any threads ffmpeg will chose automatically
665 command.outputOption('-threads ' + threads)
671 function getFFmpegVersion () {
672 return new Promise<string>((res, rej) => {
673 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
674 if (err) return rej(err)
675 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
677 return execPromise(`${ffmpegPath} -version`)
679 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
680 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
682 // Fix ffmpeg version that does not include patch version (4.4 for example)
683 let version = parsed[1]
684 if (version.match(/^\d+\.\d+$/)) {
690 .catch(err => rej(err))
695 async function runCommand (options: {
696 command: ffmpeg.FfmpegCommand
697 silent?: boolean // false
700 const { command, silent = false, job } = options
702 return new Promise<void>((res, rej) => {
703 command.on('error', (err, stdout, stderr) => {
704 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })
709 command.on('end', (stdout, stderr) => {
710 logger.debug('FFmpeg command ended.', { stdout, stderr })
716 command.on('progress', progress => {
717 if (!progress.percent) return
719 job.progress(Math.round(progress.percent))
720 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
728 // Avoid "height not divisible by 2" error
729 function getScaleCleanerValue () {
730 return 'trunc(iw/2)*2:trunc(ih/2)*2'
733 // ---------------------------------------------------------------------------
736 getLiveTranscodingCommand,
737 getLiveMuxingCommand,
741 generateImageFromVideoFile,
743 TranscodeOptionsType,
748 resetSupportedEncoders,