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, EncoderOptionsBuilder, EncoderOptions, 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'
12 import { FilterSpecification } from 'fluent-ffmpeg'
16 * Functions that run transcoding/muxing ffmpeg processes
17 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
21 // ---------------------------------------------------------------------------
23 // ---------------------------------------------------------------------------
25 type StreamType = 'audio' | 'video'
27 // ---------------------------------------------------------------------------
29 // ---------------------------------------------------------------------------
31 // Detect supported encoders by ffmpeg
32 let supportedEncoders: Map<string, boolean>
33 async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
34 if (supportedEncoders !== undefined) {
35 return supportedEncoders
38 const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
39 const availableFFmpegEncoders = await getAvailableEncodersPromise()
41 const searchEncoders = new Set<string>()
42 for (const type of [ 'live', 'vod' ]) {
43 for (const streamType of [ 'audio', 'video' ]) {
44 for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
45 searchEncoders.add(encoder)
50 supportedEncoders = new Map<string, boolean>()
52 for (const searchEncoder of searchEncoders) {
53 supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
56 logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
58 return supportedEncoders
61 function resetSupportedEncoders () {
62 supportedEncoders = undefined
65 // ---------------------------------------------------------------------------
67 // ---------------------------------------------------------------------------
69 function convertWebPToJPG (path: string, destination: string): Promise<void> {
70 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
73 return runCommand({ command, silent: true })
79 newSize: { width: number, height: number }
81 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
83 .size(`${newSize.width}x${newSize.height}`)
86 return runCommand({ command })
89 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
90 const pendingImageName = 'pending-' + imageName
93 filename: pendingImageName,
98 const pendingImagePath = join(folder, pendingImageName)
101 await new Promise<string>((res, rej) => {
102 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
104 .on('end', () => res(imageName))
108 const destination = join(folder, imageName)
109 await processImage(pendingImagePath, destination, size)
111 logger.error('Cannot generate image from video %s.', fromPath, { err })
114 await remove(pendingImagePath)
116 logger.debug('Cannot remove pending image path after generation error.', { err })
121 // ---------------------------------------------------------------------------
122 // Transcode meta function
123 // ---------------------------------------------------------------------------
125 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
127 interface BaseTranscodeOptions {
128 type: TranscodeOptionsType
133 availableEncoders: AvailableEncoders
136 resolution: VideoResolution
138 isPortraitMode?: boolean
143 interface HLSTranscodeOptions extends BaseTranscodeOptions {
147 videoFilename: string
151 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
157 videoFilename: string
161 interface QuickTranscodeOptions extends BaseTranscodeOptions {
162 type: 'quick-transcode'
165 interface VideoTranscodeOptions extends BaseTranscodeOptions {
169 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
174 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
178 type TranscodeOptions =
180 | HLSFromTSTranscodeOptions
181 | VideoTranscodeOptions
182 | MergeAudioTranscodeOptions
183 | OnlyAudioTranscodeOptions
184 | QuickTranscodeOptions
187 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
189 'quick-transcode': buildQuickTranscodeCommand,
190 'hls': buildHLSVODCommand,
191 'hls-from-ts': buildHLSVODFromTSCommand,
192 'merge-audio': buildAudioMergeCommand,
193 'only-audio': buildOnlyAudioCommand,
194 'video': buildx264VODCommand
197 async function transcode (options: TranscodeOptions) {
198 logger.debug('Will run transcode.', { options })
200 let command = getFFmpeg(options.inputPath, 'vod')
201 .output(options.outputPath)
203 command = await builders[options.type](command, options)
205 await runCommand({ command, job: options.job })
207 await fixHLSPlaylistIfNeeded(options)
210 // ---------------------------------------------------------------------------
211 // Live muxing/transcoding functions
212 // ---------------------------------------------------------------------------
214 async function getLiveTranscodingCommand (options: {
217 resolutions: number[]
220 availableEncoders: AvailableEncoders
223 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
224 const input = rtmpUrl
226 const command = getFFmpeg(input, 'live')
228 const varStreamMap: string[] = []
230 const complexFilter: FilterSpecification[] = [
234 options: resolutions.length,
235 outputs: resolutions.map(r => `vtemp${r}`)
239 command.outputOption('-preset superfast')
240 command.outputOption('-sc_threshold 0')
242 addDefaultEncoderGlobalParams({ command })
244 for (let i = 0; i < resolutions.length; i++) {
245 const resolution = resolutions[i]
246 const resolutionFPS = computeFPS(fps, resolution)
248 const baseEncoderBuilderParams = {
257 videoType: 'live' as 'live'
261 const streamType: StreamType = 'video'
262 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
263 if (!builderResult) {
264 throw new Error('No available live video encoder found')
267 command.outputOption(`-map [vout${resolution}]`)
269 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
271 logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
273 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
274 applyEncoderOptions(command, builderResult.result)
277 inputs: `vtemp${resolution}`,
278 filter: getScaleFilter(builderResult.result),
279 options: `w=-2:h=${resolution}`,
280 outputs: `vout${resolution}`
285 const streamType: StreamType = 'audio'
286 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
287 if (!builderResult) {
288 throw new Error('No available live audio encoder found')
291 command.outputOption('-map a:0')
293 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
295 logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
297 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
298 applyEncoderOptions(command, builderResult.result)
301 varStreamMap.push(`v:${i},a:${i}`)
304 command.complexFilter(complexFilter)
306 addDefaultLiveHLSParams(command, outPath)
308 command.outputOption('-var_stream_map', varStreamMap.join(' '))
313 function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
314 const command = getFFmpeg(rtmpUrl, 'live')
316 command.outputOption('-c:v copy')
317 command.outputOption('-c:a copy')
318 command.outputOption('-map 0:a?')
319 command.outputOption('-map 0:v?')
321 addDefaultLiveHLSParams(command, outPath)
326 function buildStreamSuffix (base: string, streamNum?: number) {
327 if (streamNum !== undefined) {
328 return `${base}:${streamNum}`
334 // ---------------------------------------------------------------------------
336 // ---------------------------------------------------------------------------
338 function addDefaultEncoderGlobalParams (options: {
339 command: ffmpeg.FfmpegCommand
341 const { command } = options
343 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
344 command.outputOption('-max_muxing_queue_size 1024')
345 // strip all metadata
346 .outputOption('-map_metadata -1')
347 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
348 .outputOption('-b_strategy 1')
349 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
350 .outputOption('-bf 16')
351 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
352 .outputOption('-pix_fmt yuv420p')
355 function addDefaultEncoderParams (options: {
356 command: ffmpeg.FfmpegCommand
357 encoder: 'libx264' | string
361 const { command, encoder, fps, streamNum } = options
363 if (encoder === 'libx264') {
364 // 3.1 is the minimal resource allocation for our highest supported resolution
365 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
368 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
369 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
370 // https://superuser.com/a/908325
371 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
376 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
377 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
378 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
379 command.outputOption('-hls_flags delete_segments+independent_segments')
380 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
381 command.outputOption('-master_pl_name master.m3u8')
382 command.outputOption(`-f hls`)
384 command.output(join(outPath, '%v.m3u8'))
387 // ---------------------------------------------------------------------------
388 // Transcode VOD command builders
389 // ---------------------------------------------------------------------------
391 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
392 let fps = await getVideoFileFPS(options.inputPath)
393 fps = computeFPS(fps, options.resolution)
395 let scaleFilterValue: string
397 if (options.resolution !== undefined) {
398 scaleFilterValue = options.isPortraitMode === true
399 ? `w=${options.resolution}:h=-2`
400 : `w=-2:h=${options.resolution}`
403 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
408 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
409 command = command.loop(undefined)
411 // Avoid "height not divisible by 2" error
412 const scaleFilterValue = 'trunc(iw/2)*2:trunc(ih/2)*2'
413 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
415 command.outputOption('-preset:v veryfast')
417 command = command.input(options.audioPath)
418 .outputOption('-tune stillimage')
419 .outputOption('-shortest')
424 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
425 command = presetOnlyAudio(command)
430 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
431 command = presetCopy(command)
433 command = command.outputOption('-map_metadata -1') // strip all metadata
434 .outputOption('-movflags faststart')
439 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
440 return command.outputOption('-hls_time 4')
441 .outputOption('-hls_list_size 0')
442 .outputOption('-hls_playlist_type vod')
443 .outputOption('-hls_segment_filename ' + outputPath)
444 .outputOption('-hls_segment_type fmp4')
445 .outputOption('-f hls')
446 .outputOption('-hls_flags single_file')
449 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
450 const videoPath = getHLSVideoPath(options)
452 if (options.copyCodecs) command = presetCopy(command)
453 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
454 else command = await buildx264VODCommand(command, options)
456 addCommonHLSVODCommandOptions(command, videoPath)
461 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
462 const videoPath = getHLSVideoPath(options)
464 command.outputOption('-c copy')
467 // Required for example when copying an AAC stream from an MPEG-TS
468 // Since it's a bitstream filter, we don't need to reencode the audio
469 command.outputOption('-bsf:a aac_adtstoasc')
472 addCommonHLSVODCommandOptions(command, videoPath)
477 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
478 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
480 const fileContent = await readFile(options.outputPath)
482 const videoFileName = options.hlsPlaylist.videoFilename
483 const videoFilePath = getHLSVideoPath(options)
485 // Fix wrong mapping with some ffmpeg versions
486 const newContent = fileContent.toString()
487 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
489 await writeFile(options.outputPath, newContent)
492 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
493 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
496 // ---------------------------------------------------------------------------
497 // Transcoding presets
498 // ---------------------------------------------------------------------------
500 // Run encoder builder depending on available encoders
501 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
502 // If the default one does not exist, check the next encoder
503 async function getEncoderBuilderResult (options: {
504 streamType: 'video' | 'audio'
507 availableEncoders: AvailableEncoders
510 videoType: 'vod' | 'live'
516 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
518 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
519 const encoders = availableEncoders.available[videoType]
521 for (const encoder of encodersToTry) {
522 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
523 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
527 if (!encoders[encoder]) {
528 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
532 // An object containing available profiles for this encoder
533 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
534 let builder = builderProfiles[profile]
537 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
538 builder = builderProfiles.default
541 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
546 const result = await builder({ input, resolution: resolution, fps, streamNum })
551 // If we don't have output options, then copy the input stream
552 encoder: result.copy === true
561 async function presetVideo (options: {
562 command: ffmpeg.FfmpegCommand
564 transcodeOptions: TranscodeOptions
566 scaleFilterValue?: string
568 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
570 let localCommand = command
572 .outputOption('-movflags faststart')
574 addDefaultEncoderGlobalParams({ command })
577 const parsedAudio = await getAudioStream(input)
579 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
581 if (!parsedAudio.audioStream) {
582 localCommand = localCommand.noAudio()
583 streamsToProcess = [ 'video' ]
586 for (const streamType of streamsToProcess) {
587 const { profile, resolution, availableEncoders } = transcodeOptions
589 const builderResult = await getEncoderBuilderResult({
596 videoType: 'vod' as 'vod'
599 if (!builderResult) {
600 throw new Error('No available encoder found for stream ' + streamType)
604 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
605 builderResult.encoder, streamType, input, profile, builderResult
608 if (streamType === 'video') {
609 localCommand.videoCodec(builderResult.encoder)
611 if (scaleFilterValue) {
612 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
614 } else if (streamType === 'audio') {
615 localCommand.audioCodec(builderResult.encoder)
618 applyEncoderOptions(localCommand, builderResult.result)
619 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
625 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
632 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
639 function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
641 .inputOptions(options.inputOptions ?? [])
642 .outputOptions(options.outputOptions ?? [])
645 function getScaleFilter (options: EncoderOptions): string {
646 if (options.scaleFilter) return options.scaleFilter.name
651 // ---------------------------------------------------------------------------
653 // ---------------------------------------------------------------------------
655 function getFFmpeg (input: string, type: 'live' | 'vod') {
656 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
657 const command = ffmpeg(input, {
658 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
659 cwd: CONFIG.STORAGE.TMP_DIR
662 const threads = type === 'live'
663 ? CONFIG.LIVE.TRANSCODING.THREADS
664 : CONFIG.TRANSCODING.THREADS
667 // If we don't set any threads ffmpeg will chose automatically
668 command.outputOption('-threads ' + threads)
674 function getFFmpegVersion () {
675 return new Promise<string>((res, rej) => {
676 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
677 if (err) return rej(err)
678 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
680 return execPromise(`${ffmpegPath} -version`)
682 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+\.\d+)/)
683 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
685 return res(parsed[1])
687 .catch(err => rej(err))
692 async function runCommand (options: {
693 command: ffmpeg.FfmpegCommand
694 silent?: boolean // false
697 const { command, silent = false, job } = options
699 return new Promise<void>((res, rej) => {
700 command.on('error', (err, stdout, stderr) => {
701 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })
706 command.on('end', (stdout, stderr) => {
707 logger.debug('FFmpeg command ended.', { stdout, stderr })
713 command.on('progress', progress => {
714 if (!progress.percent) return
716 job.progress(Math.round(progress.percent))
717 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
725 // ---------------------------------------------------------------------------
728 getLiveTranscodingCommand,
729 getLiveMuxingCommand,
733 generateImageFromVideoFile,
735 TranscodeOptionsType,
740 resetSupportedEncoders,