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 { VideoResolution } from '../../shared/models/videos'
7 import { checkFFmpegEncoders } from '../initializers/checker-before-init'
8 import { CONFIG } from '../initializers/config'
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 // ---------------------------------------------------------------------------
26 export type EncoderOptionsBuilder = (params: {
28 resolution: VideoResolution
31 }) => Promise<EncoderOptions> | EncoderOptions
35 export interface EncoderOptions {
37 outputOptions: string[]
42 export interface EncoderProfile <T> {
43 [ profile: string ]: T
48 export type AvailableEncoders = {
50 [ encoder: string ]: EncoderProfile<EncoderOptionsBuilder>
54 [ encoder: string ]: EncoderProfile<EncoderOptionsBuilder>
63 type StreamType = 'audio' | 'video'
65 // ---------------------------------------------------------------------------
67 // ---------------------------------------------------------------------------
69 function convertWebPToJPG (path: string, destination: string): Promise<void> {
70 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
73 return runCommand(command)
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, 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 command.complexFilter([
234 options: resolutions.length,
235 outputs: resolutions.map(r => `vtemp${r}`)
238 ...resolutions.map(r => ({
241 options: `w=-2:h=${r}`,
246 command.outputOption('-preset superfast')
247 command.outputOption('-sc_threshold 0')
249 addDefaultEncoderGlobalParams({ command })
251 for (let i = 0; i < resolutions.length; i++) {
252 const resolution = resolutions[i]
253 const resolutionFPS = computeFPS(fps, resolution)
255 const baseEncoderBuilderParams = {
264 videoType: 'live' as 'live'
268 const streamType: StreamType = 'video'
269 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
270 if (!builderResult) {
271 throw new Error('No available live video encoder found')
274 command.outputOption(`-map [vout${resolution}]`)
276 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
278 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
280 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
281 command.addOutputOptions(builderResult.result.outputOptions)
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.', builderResult.encoder, builderResult)
297 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
298 command.addOutputOptions(builderResult.result.outputOptions)
301 varStreamMap.push(`v:${i},a:${i}`)
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 command = await presetVideo(command, options.inputPath, options, fps)
395 if (options.resolution !== undefined) {
396 // '?x720' or '720x?' for example
397 const size = options.isPortraitMode === true
398 ? `${options.resolution}x?`
399 : `?x${options.resolution}`
401 command = command.size(size)
407 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
408 command = command.loop(undefined)
410 command = await presetVideo(command, options.audioPath, options)
412 command.outputOption('-preset:v veryfast')
414 command = command.input(options.audioPath)
415 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
416 .outputOption('-tune stillimage')
417 .outputOption('-shortest')
422 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
423 command = presetOnlyAudio(command)
428 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
429 command = presetCopy(command)
431 command = command.outputOption('-map_metadata -1') // strip all metadata
432 .outputOption('-movflags faststart')
437 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
438 return command.outputOption('-hls_time 4')
439 .outputOption('-hls_list_size 0')
440 .outputOption('-hls_playlist_type vod')
441 .outputOption('-hls_segment_filename ' + outputPath)
442 .outputOption('-hls_segment_type fmp4')
443 .outputOption('-f hls')
444 .outputOption('-hls_flags single_file')
447 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
448 const videoPath = getHLSVideoPath(options)
450 if (options.copyCodecs) command = presetCopy(command)
451 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
452 else command = await buildx264VODCommand(command, options)
454 addCommonHLSVODCommandOptions(command, videoPath)
459 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
460 const videoPath = getHLSVideoPath(options)
462 command.outputOption('-c copy')
465 // Required for example when copying an AAC stream from an MPEG-TS
466 // Since it's a bitstream filter, we don't need to reencode the audio
467 command.outputOption('-bsf:a aac_adtstoasc')
470 addCommonHLSVODCommandOptions(command, videoPath)
475 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
476 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
478 const fileContent = await readFile(options.outputPath)
480 const videoFileName = options.hlsPlaylist.videoFilename
481 const videoFilePath = getHLSVideoPath(options)
483 // Fix wrong mapping with some ffmpeg versions
484 const newContent = fileContent.toString()
485 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
487 await writeFile(options.outputPath, newContent)
490 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
491 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
494 // ---------------------------------------------------------------------------
495 // Transcoding presets
496 // ---------------------------------------------------------------------------
498 // Run encoder builder depending on available encoders
499 // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
500 // If the default one does not exist, check the next encoder
501 async function getEncoderBuilderResult (options: {
502 streamType: 'video' | 'audio'
505 availableEncoders: AvailableEncoders
508 videoType: 'vod' | 'live'
514 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
516 const encodersToTry = availableEncoders.encodersToTry[streamType]
517 const encoders = availableEncoders[videoType]
519 for (const encoder of encodersToTry) {
520 if (!(await checkFFmpegEncoders()).get(encoder) || !encoders[encoder]) continue
522 // An object containing available profiles for this encoder
523 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
524 let builder = builderProfiles[profile]
527 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
528 builder = builderProfiles.default
531 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
536 const result = await builder({ input, resolution: resolution, fps, streamNum })
541 // If we don't have output options, then copy the input stream
542 encoder: result.copy === true
551 async function presetVideo (
552 command: ffmpeg.FfmpegCommand,
554 transcodeOptions: TranscodeOptions,
557 let localCommand = command
559 .outputOption('-movflags faststart')
561 addDefaultEncoderGlobalParams({ command })
564 const parsedAudio = await getAudioStream(input)
566 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
568 if (!parsedAudio.audioStream) {
569 localCommand = localCommand.noAudio()
570 streamsToProcess = [ 'audio' ]
573 for (const streamType of streamsToProcess) {
574 const { profile, resolution, availableEncoders } = transcodeOptions
576 const builderResult = await getEncoderBuilderResult({
583 videoType: 'vod' as 'vod'
586 if (!builderResult) {
587 throw new Error('No available encoder found for stream ' + streamType)
590 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
592 if (streamType === 'video') {
593 localCommand.videoCodec(builderResult.encoder)
594 } else if (streamType === 'audio') {
595 localCommand.audioCodec(builderResult.encoder)
598 command.addOutputOptions(builderResult.result.outputOptions)
599 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
605 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
612 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
619 // ---------------------------------------------------------------------------
621 // ---------------------------------------------------------------------------
623 function getFFmpeg (input: string, type: 'live' | 'vod') {
624 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
625 const command = ffmpeg(input, {
626 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
627 cwd: CONFIG.STORAGE.TMP_DIR
630 const threads = type === 'live'
631 ? CONFIG.LIVE.TRANSCODING.THREADS
632 : CONFIG.TRANSCODING.THREADS
635 // If we don't set any threads ffmpeg will chose automatically
636 command.outputOption('-threads ' + threads)
642 async function runCommand (command: ffmpeg.FfmpegCommand, job?: Job) {
643 return new Promise<void>((res, rej) => {
644 command.on('error', (err, stdout, stderr) => {
645 logger.error('Error in transcoding job.', { stdout, stderr })
649 command.on('end', (stdout, stderr) => {
650 logger.debug('FFmpeg command ended.', { stdout, stderr })
656 command.on('progress', progress => {
657 if (!progress.percent) return
659 job.progress(Math.round(progress.percent))
660 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
668 // ---------------------------------------------------------------------------
671 getLiveTranscodingCommand,
672 getLiveMuxingCommand,
676 generateImageFromVideoFile,
678 TranscodeOptionsType,