1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { readFile, remove, writeFile } from 'fs-extra'
3 import { dirname, join } from 'path'
4 import { FFMPEG_NICE, VIDEO_LIVE, VIDEO_TRANSCODING_ENCODERS } from '@server/initializers/constants'
5 import { VideoResolution } from '../../shared/models/videos'
6 import { checkFFmpegEncoders } from '../initializers/checker-before-init'
7 import { CONFIG } from '../initializers/config'
8 import { computeFPS, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
9 import { processImage } from './image-utils'
10 import { logger } from './logger'
14 * Functions that run transcoding/muxing ffmpeg processes
15 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
19 // ---------------------------------------------------------------------------
21 // ---------------------------------------------------------------------------
25 export type EncoderOptionsBuilder = (params: {
27 resolution: VideoResolution
30 }) => Promise<EncoderOptions> | EncoderOptions
34 export interface EncoderOptions {
36 outputOptions: string[]
41 export interface EncoderProfile <T> {
42 [ profile: string ]: T
47 export type AvailableEncoders = {
48 [ id in 'live' | 'vod' ]: {
49 [ encoder in 'libx264' | 'aac' | 'libfdk_aac' ]?: EncoderProfile<EncoderOptionsBuilder>
53 // ---------------------------------------------------------------------------
55 // ---------------------------------------------------------------------------
57 function convertWebPToJPG (path: string, destination: string): Promise<void> {
58 const command = ffmpeg(path)
61 return runCommand(command)
67 newSize: { width: number, height: number }
69 const command = ffmpeg(path)
71 .size(`${newSize.width}x${newSize.height}`)
74 return runCommand(command)
77 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
78 const pendingImageName = 'pending-' + imageName
81 filename: pendingImageName,
86 const pendingImagePath = join(folder, pendingImageName)
89 await new Promise<string>((res, rej) => {
90 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
92 .on('end', () => res(imageName))
96 const destination = join(folder, imageName)
97 await processImage(pendingImagePath, destination, size)
99 logger.error('Cannot generate image from video %s.', fromPath, { err })
102 await remove(pendingImagePath)
104 logger.debug('Cannot remove pending image path after generation error.', { err })
109 // ---------------------------------------------------------------------------
110 // Transcode meta function
111 // ---------------------------------------------------------------------------
113 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
115 interface BaseTranscodeOptions {
116 type: TranscodeOptionsType
121 availableEncoders: AvailableEncoders
124 resolution: VideoResolution
126 isPortraitMode?: boolean
129 interface HLSTranscodeOptions extends BaseTranscodeOptions {
133 videoFilename: string
137 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
143 videoFilename: string
147 interface QuickTranscodeOptions extends BaseTranscodeOptions {
148 type: 'quick-transcode'
151 interface VideoTranscodeOptions extends BaseTranscodeOptions {
155 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
160 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
164 type TranscodeOptions =
166 | HLSFromTSTranscodeOptions
167 | VideoTranscodeOptions
168 | MergeAudioTranscodeOptions
169 | OnlyAudioTranscodeOptions
170 | QuickTranscodeOptions
173 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
175 'quick-transcode': buildQuickTranscodeCommand,
176 'hls': buildHLSVODCommand,
177 'hls-from-ts': buildHLSVODFromTSCommand,
178 'merge-audio': buildAudioMergeCommand,
179 'only-audio': buildOnlyAudioCommand,
180 'video': buildx264VODCommand
183 async function transcode (options: TranscodeOptions) {
184 logger.debug('Will run transcode.', { options })
186 let command = getFFmpeg(options.inputPath, 'vod')
187 .output(options.outputPath)
189 command = await builders[options.type](command, options)
191 await runCommand(command)
193 await fixHLSPlaylistIfNeeded(options)
196 // ---------------------------------------------------------------------------
197 // Live muxing/transcoding functions
198 // ---------------------------------------------------------------------------
200 async function getLiveTranscodingCommand (options: {
203 resolutions: number[]
206 availableEncoders: AvailableEncoders
209 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
210 const input = rtmpUrl
212 const command = getFFmpeg(input, 'live')
214 const varStreamMap: string[] = []
216 command.complexFilter([
220 options: resolutions.length,
221 outputs: resolutions.map(r => `vtemp${r}`)
224 ...resolutions.map(r => ({
227 options: `w=-2:h=${r}`,
232 command.outputOption('-preset superfast')
233 command.outputOption('-sc_threshold 0')
235 addDefaultEncoderGlobalParams({ command })
237 for (let i = 0; i < resolutions.length; i++) {
238 const resolution = resolutions[i]
239 const resolutionFPS = computeFPS(fps, resolution)
241 const baseEncoderBuilderParams = {
248 videoType: 'live' as 'live'
252 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' }))
253 if (!builderResult) {
254 throw new Error('No available live video encoder found')
257 command.outputOption(`-map [vout${resolution}]`)
259 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
261 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
263 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
264 command.addOutputOptions(builderResult.result.outputOptions)
268 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' }))
269 if (!builderResult) {
270 throw new Error('No available live audio encoder found')
273 command.outputOption('-map a:0')
275 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
277 logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult)
279 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
280 command.addOutputOptions(builderResult.result.outputOptions)
283 varStreamMap.push(`v:${i},a:${i}`)
286 addDefaultLiveHLSParams(command, outPath)
288 command.outputOption('-var_stream_map', varStreamMap.join(' '))
293 function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
294 const command = getFFmpeg(rtmpUrl, 'live')
296 command.outputOption('-c:v copy')
297 command.outputOption('-c:a copy')
298 command.outputOption('-map 0:a?')
299 command.outputOption('-map 0:v?')
301 addDefaultLiveHLSParams(command, outPath)
306 function buildStreamSuffix (base: string, streamNum?: number) {
307 if (streamNum !== undefined) {
308 return `${base}:${streamNum}`
314 // ---------------------------------------------------------------------------
317 getLiveTranscodingCommand,
318 getLiveMuxingCommand,
322 generateImageFromVideoFile,
324 TranscodeOptionsType,
328 // ---------------------------------------------------------------------------
330 // ---------------------------------------------------------------------------
332 // ---------------------------------------------------------------------------
334 function addDefaultEncoderGlobalParams (options: {
335 command: ffmpeg.FfmpegCommand
337 const { command } = options
339 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
340 command.outputOption('-max_muxing_queue_size 1024')
341 // strip all metadata
342 .outputOption('-map_metadata -1')
343 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
344 .outputOption('-b_strategy 1')
345 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
346 .outputOption('-bf 16')
347 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
348 .outputOption('-pix_fmt yuv420p')
351 function addDefaultEncoderParams (options: {
352 command: ffmpeg.FfmpegCommand
353 encoder: 'libx264' | string
357 const { command, encoder, fps, streamNum } = options
359 if (encoder === 'libx264') {
360 // 3.1 is the minimal resource allocation for our highest supported resolution
361 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
364 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
365 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
366 // https://superuser.com/a/908325
367 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
372 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
373 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
374 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
375 command.outputOption('-hls_flags delete_segments+independent_segments')
376 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
377 command.outputOption('-master_pl_name master.m3u8')
378 command.outputOption(`-f hls`)
380 command.output(join(outPath, '%v.m3u8'))
383 // ---------------------------------------------------------------------------
384 // Transcode VOD command builders
385 // ---------------------------------------------------------------------------
387 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
388 let fps = await getVideoFileFPS(options.inputPath)
389 fps = computeFPS(fps, options.resolution)
391 command = await presetVideo(command, options.inputPath, options, fps)
393 if (options.resolution !== undefined) {
394 // '?x720' or '720x?' for example
395 const size = options.isPortraitMode === true
396 ? `${options.resolution}x?`
397 : `?x${options.resolution}`
399 command = command.size(size)
405 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
406 command = command.loop(undefined)
408 command = await presetVideo(command, options.audioPath, options)
410 command.outputOption('-preset:v veryfast')
412 command = command.input(options.audioPath)
413 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
414 .outputOption('-tune stillimage')
415 .outputOption('-shortest')
420 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
421 command = presetOnlyAudio(command)
426 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
427 command = presetCopy(command)
429 command = command.outputOption('-map_metadata -1') // strip all metadata
430 .outputOption('-movflags faststart')
435 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
436 return command.outputOption('-hls_time 4')
437 .outputOption('-hls_list_size 0')
438 .outputOption('-hls_playlist_type vod')
439 .outputOption('-hls_segment_filename ' + outputPath)
440 .outputOption('-hls_segment_type fmp4')
441 .outputOption('-f hls')
442 .outputOption('-hls_flags single_file')
445 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
446 const videoPath = getHLSVideoPath(options)
448 if (options.copyCodecs) command = presetCopy(command)
449 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
450 else command = await buildx264VODCommand(command, options)
452 addCommonHLSVODCommandOptions(command, videoPath)
457 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
458 const videoPath = getHLSVideoPath(options)
460 command.outputOption('-c copy')
463 // Required for example when copying an AAC stream from an MPEG-TS
464 // Since it's a bitstream filter, we don't need to reencode the audio
465 command.outputOption('-bsf:a aac_adtstoasc')
468 addCommonHLSVODCommandOptions(command, videoPath)
473 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
474 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
476 const fileContent = await readFile(options.outputPath)
478 const videoFileName = options.hlsPlaylist.videoFilename
479 const videoFilePath = getHLSVideoPath(options)
481 // Fix wrong mapping with some ffmpeg versions
482 const newContent = fileContent.toString()
483 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
485 await writeFile(options.outputPath, newContent)
488 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
489 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
492 // ---------------------------------------------------------------------------
493 // Transcoding presets
494 // ---------------------------------------------------------------------------
496 async function getEncoderBuilderResult (options: {
500 availableEncoders: AvailableEncoders
503 videoType: 'vod' | 'live'
509 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
511 const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType]
513 for (const encoder of encodersToTry) {
514 if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue
516 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder]
517 let builder = builderProfiles[profile]
520 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
521 builder = builderProfiles.default
524 const result = await builder({ input, resolution: resolution, fps, streamNum })
529 // If we don't have output options, then copy the input stream
530 encoder: result.copy === true
539 async function presetVideo (
540 command: ffmpeg.FfmpegCommand,
542 transcodeOptions: TranscodeOptions,
545 let localCommand = command
547 .outputOption('-movflags faststart')
549 addDefaultEncoderGlobalParams({ command })
552 const parsedAudio = await getAudioStream(input)
554 let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
556 if (!parsedAudio.audioStream) {
557 localCommand = localCommand.noAudio()
558 streamsToProcess = [ 'VIDEO' ]
561 for (const streamType of streamsToProcess) {
562 const { profile, resolution, availableEncoders } = transcodeOptions
564 const builderResult = await getEncoderBuilderResult({
571 videoType: 'vod' as 'vod'
574 if (!builderResult) {
575 throw new Error('No available encoder found for stream ' + streamType)
578 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
580 if (streamType === 'VIDEO') {
581 localCommand.videoCodec(builderResult.encoder)
582 } else if (streamType === 'AUDIO') {
583 localCommand.audioCodec(builderResult.encoder)
586 command.addOutputOptions(builderResult.result.outputOptions)
587 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
593 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
600 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
607 // ---------------------------------------------------------------------------
609 // ---------------------------------------------------------------------------
611 function getFFmpeg (input: string, type: 'live' | 'vod') {
612 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
613 const command = ffmpeg(input, { niceness: FFMPEG_NICE.TRANSCODING, cwd: CONFIG.STORAGE.TMP_DIR })
615 const threads = type === 'live'
616 ? CONFIG.LIVE.TRANSCODING.THREADS
617 : CONFIG.TRANSCODING.THREADS
620 // If we don't set any threads ffmpeg will chose automatically
621 command.outputOption('-threads ' + threads)
627 async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
628 return new Promise<void>((res, rej) => {
629 command.on('error', (err, stdout, stderr) => {
632 logger.error('Error in transcoding job.', { stdout, stderr })
636 command.on('end', () => {