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, VIDEO_TRANSCODING_FPS } 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 { getAudioStream, getClosestFramerateStandard, 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' | '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 QuickTranscodeOptions extends BaseTranscodeOptions {
138 type: 'quick-transcode'
141 interface VideoTranscodeOptions extends BaseTranscodeOptions {
145 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
150 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
154 type TranscodeOptions =
156 | VideoTranscodeOptions
157 | MergeAudioTranscodeOptions
158 | OnlyAudioTranscodeOptions
159 | QuickTranscodeOptions
162 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
164 'quick-transcode': buildQuickTranscodeCommand,
165 'hls': buildHLSVODCommand,
166 'merge-audio': buildAudioMergeCommand,
167 'only-audio': buildOnlyAudioCommand,
168 'video': buildx264VODCommand
171 async function transcode (options: TranscodeOptions) {
172 logger.debug('Will run transcode.', { options })
174 let command = getFFmpeg(options.inputPath)
175 .output(options.outputPath)
177 command = await builders[options.type](command, options)
179 await runCommand(command)
181 await fixHLSPlaylistIfNeeded(options)
184 // ---------------------------------------------------------------------------
185 // Live muxing/transcoding functions
186 // ---------------------------------------------------------------------------
188 async function getLiveTranscodingCommand (options: {
191 resolutions: number[]
193 deleteSegments: boolean
195 availableEncoders: AvailableEncoders
198 const { rtmpUrl, outPath, resolutions, fps, deleteSegments, availableEncoders, profile } = options
199 const input = rtmpUrl
201 const command = getFFmpeg(input)
202 command.inputOption('-fflags nobuffer')
204 const varStreamMap: string[] = []
206 command.complexFilter([
210 options: resolutions.length,
211 outputs: resolutions.map(r => `vtemp${r}`)
214 ...resolutions.map(r => ({
217 options: `w=-2:h=${r}`,
222 command.outputOption('-preset superfast')
224 for (let i = 0; i < resolutions.length; i++) {
225 const resolution = resolutions[i]
226 const baseEncoderBuilderParams = { input, availableEncoders, profile, fps, resolution, streamNum: i, videoType: 'live' as 'live' }
229 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' }))
230 if (!builderResult) {
231 throw new Error('No available live video encoder found')
234 command.outputOption(`-map [vout${resolution}]`)
236 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps, streamNum: i })
238 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
240 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
241 command.addOutputOptions(builderResult.result.outputOptions)
245 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' }))
246 if (!builderResult) {
247 throw new Error('No available live audio encoder found')
250 command.outputOption('-map a:0')
252 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps, streamNum: i })
254 logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult)
256 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
257 command.addOutputOptions(builderResult.result.outputOptions)
260 varStreamMap.push(`v:${i},a:${i}`)
263 addDefaultLiveHLSParams(command, outPath, deleteSegments)
265 command.outputOption('-var_stream_map', varStreamMap.join(' '))
270 function getLiveMuxingCommand (rtmpUrl: string, outPath: string, deleteSegments: boolean) {
271 const command = getFFmpeg(rtmpUrl)
272 command.inputOption('-fflags nobuffer')
274 command.outputOption('-c:v copy')
275 command.outputOption('-c:a copy')
276 command.outputOption('-map 0:a?')
277 command.outputOption('-map 0:v?')
279 addDefaultLiveHLSParams(command, outPath, deleteSegments)
284 async function hlsPlaylistToFragmentedMP4 (hlsDirectory: string, segmentFiles: string[], outputPath: string) {
285 const concatFilePath = join(hlsDirectory, 'concat.txt')
287 function cleaner () {
288 remove(concatFilePath)
289 .catch(err => logger.error('Cannot remove concat file in %s.', hlsDirectory, { err }))
292 // First concat the ts files to a mp4 file
293 const content = segmentFiles.map(f => 'file ' + f)
296 await writeFile(concatFilePath, content + '\n')
298 const command = getFFmpeg(concatFilePath)
299 command.inputOption('-safe 0')
300 command.inputOption('-f concat')
302 command.outputOption('-c:v copy')
303 command.audioFilter('aresample=async=1:first_pts=0')
304 command.output(outputPath)
306 return runCommand(command, cleaner)
309 function buildStreamSuffix (base: string, streamNum?: number) {
310 if (streamNum !== undefined) {
311 return `${base}:${streamNum}`
317 // ---------------------------------------------------------------------------
320 getLiveTranscodingCommand,
321 getLiveMuxingCommand,
325 generateImageFromVideoFile,
327 TranscodeOptionsType,
329 hlsPlaylistToFragmentedMP4
332 // ---------------------------------------------------------------------------
334 // ---------------------------------------------------------------------------
336 // ---------------------------------------------------------------------------
338 function addDefaultEncoderParams (options: {
339 command: ffmpeg.FfmpegCommand
340 encoder: 'libx264' | string
344 const { command, encoder, fps, streamNum } = options
346 if (encoder === 'libx264') {
347 // 3.1 is the minimal resource allocation for our highest supported resolution
348 command.outputOption('-level 3.1')
349 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
350 .outputOption('-b_strategy 1')
351 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
352 .outputOption('-bf 16')
353 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
354 .outputOption(buildStreamSuffix('-pix_fmt', streamNum) + ' yuv420p')
355 // strip all metadata
356 .outputOption('-map_metadata -1')
357 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
358 .outputOption(buildStreamSuffix('-max_muxing_queue_size', streamNum) + ' 1024')
361 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
362 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
363 // https://superuser.com/a/908325
364 command.outputOption('-g ' + (fps * 2))
369 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, deleteSegments: boolean) {
370 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
371 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
373 if (deleteSegments === true) {
374 command.outputOption('-hls_flags delete_segments')
377 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
378 command.outputOption('-master_pl_name master.m3u8')
379 command.outputOption(`-f hls`)
381 command.output(join(outPath, '%v.m3u8'))
384 // ---------------------------------------------------------------------------
385 // Transcode VOD command builders
386 // ---------------------------------------------------------------------------
388 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
389 let fps = await getVideoFileFPS(options.inputPath)
391 // On small/medium resolutions, limit FPS
392 options.resolution !== undefined &&
393 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
394 fps > VIDEO_TRANSCODING_FPS.AVERAGE
396 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
397 fps = getClosestFramerateStandard(fps, 'STANDARD')
400 command = await presetVideo(command, options.inputPath, options, fps)
402 if (options.resolution !== undefined) {
403 // '?x720' or '720x?' for example
404 const size = options.isPortraitMode === true
405 ? `${options.resolution}x?`
406 : `?x${options.resolution}`
408 command = command.size(size)
412 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
413 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
415 command = command.withFPS(fps)
420 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
421 command = command.loop(undefined)
423 command = await presetVideo(command, options.audioPath, options)
426 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
427 Our target situation is closer to a livestream than a stream,
428 since we want to reduce as much a possible the encoding burden,
429 although not to the point of a livestream where there is a hard
430 constraint on the frames per second to be encoded.
432 command.outputOption('-preset:v veryfast')
434 command = command.input(options.audioPath)
435 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
436 .outputOption('-tune stillimage')
437 .outputOption('-shortest')
442 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
443 command = presetOnlyAudio(command)
448 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
449 command = presetCopy(command)
451 command = command.outputOption('-map_metadata -1') // strip all metadata
452 .outputOption('-movflags faststart')
457 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
458 const videoPath = getHLSVideoPath(options)
460 if (options.copyCodecs) command = presetCopy(command)
461 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
462 else command = await buildx264VODCommand(command, options)
464 command = command.outputOption('-hls_time 4')
465 .outputOption('-hls_list_size 0')
466 .outputOption('-hls_playlist_type vod')
467 .outputOption('-hls_segment_filename ' + videoPath)
468 .outputOption('-hls_segment_type fmp4')
469 .outputOption('-f hls')
470 .outputOption('-hls_flags single_file')
475 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
476 if (options.type !== 'hls') 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) {
491 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
494 // ---------------------------------------------------------------------------
495 // Transcoding presets
496 // ---------------------------------------------------------------------------
498 async function getEncoderBuilderResult (options: {
502 availableEncoders: AvailableEncoders
505 videoType: 'vod' | 'live'
511 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
513 const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType]
515 for (const encoder of encodersToTry) {
516 if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue
518 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder]
519 let builder = builderProfiles[profile]
522 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
523 builder = builderProfiles.default
526 const result = await builder({ input, resolution: resolution, fps, streamNum })
531 // If we don't have output options, then copy the input stream
532 encoder: result.copy === true
541 async function presetVideo (
542 command: ffmpeg.FfmpegCommand,
544 transcodeOptions: TranscodeOptions,
547 let localCommand = command
549 .outputOption('-movflags faststart')
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) {
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 if (CONFIG.TRANSCODING.THREADS > 0) {
616 // If we don't set any threads ffmpeg will chose automatically
617 command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
623 async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
624 return new Promise<void>((res, rej) => {
625 command.on('error', (err, stdout, stderr) => {
628 logger.error('Error in transcoding job.', { stdout, stderr })
632 command.on('end', () => {