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'
12 // ---------------------------------------------------------------------------
14 // ---------------------------------------------------------------------------
18 export type EncoderOptionsBuilder = (params: {
20 resolution: VideoResolution
23 }) => Promise<EncoderOptions> | EncoderOptions
27 export interface EncoderOptions {
29 outputOptions: string[]
34 export interface EncoderProfile <T> {
35 [ profile: string ]: T
40 export type AvailableEncoders = {
41 [ id in 'live' | 'vod' ]: {
42 [ encoder in 'libx264' | 'aac' | 'libfdk_aac' ]?: EncoderProfile<EncoderOptionsBuilder>
46 // ---------------------------------------------------------------------------
48 // ---------------------------------------------------------------------------
50 function convertWebPToJPG (path: string, destination: string): Promise<void> {
51 const command = ffmpeg(path)
54 return runCommand(command)
60 newSize: { width: number, height: number },
63 return new Promise<void>(async (res, rej) => {
64 if (path === destination) {
65 throw new Error('FFmpeg needs an input path different that the output path.')
68 logger.debug('Processing gif %s to %s.', path, destination)
71 const command = ffmpeg(path)
73 .size(`${newSize.width}x${newSize.height}`)
76 command.on('error', (err, stdout, stderr) => {
77 logger.error('Error in ffmpeg gif resizing process.', { stdout, stderr })
80 .on('end', async () => {
81 if (keepOriginal !== true) await remove(path)
91 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
92 const pendingImageName = 'pending-' + imageName
95 filename: pendingImageName,
100 const pendingImagePath = join(folder, pendingImageName)
103 await new Promise<string>((res, rej) => {
104 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
106 .on('end', () => res(imageName))
110 const destination = join(folder, imageName)
111 await processImage(pendingImagePath, destination, size)
113 logger.error('Cannot generate image from video %s.', fromPath, { err })
116 await remove(pendingImagePath)
118 logger.debug('Cannot remove pending image path after generation error.', { err })
123 // ---------------------------------------------------------------------------
124 // Transcode meta function
125 // ---------------------------------------------------------------------------
127 type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
129 interface BaseTranscodeOptions {
130 type: TranscodeOptionsType
135 availableEncoders: AvailableEncoders
138 resolution: VideoResolution
140 isPortraitMode?: boolean
143 interface HLSTranscodeOptions extends BaseTranscodeOptions {
147 videoFilename: string
151 interface QuickTranscodeOptions extends BaseTranscodeOptions {
152 type: 'quick-transcode'
155 interface VideoTranscodeOptions extends BaseTranscodeOptions {
159 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
164 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
168 type TranscodeOptions =
170 | VideoTranscodeOptions
171 | MergeAudioTranscodeOptions
172 | OnlyAudioTranscodeOptions
173 | QuickTranscodeOptions
176 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
178 'quick-transcode': buildQuickTranscodeCommand,
179 'hls': buildHLSVODCommand,
180 'merge-audio': buildAudioMergeCommand,
181 'only-audio': buildOnlyAudioCommand,
182 'video': buildx264VODCommand
185 async function transcode (options: TranscodeOptions) {
186 logger.debug('Will run transcode.', { options })
188 let command = getFFmpeg(options.inputPath)
189 .output(options.outputPath)
191 command = await builders[options.type](command, options)
193 await runCommand(command)
195 await fixHLSPlaylistIfNeeded(options)
198 // ---------------------------------------------------------------------------
199 // Live muxing/transcoding functions
200 // ---------------------------------------------------------------------------
202 async function getLiveTranscodingCommand (options: {
205 resolutions: number[]
207 deleteSegments: boolean
209 availableEncoders: AvailableEncoders
212 const { rtmpUrl, outPath, resolutions, fps, deleteSegments, availableEncoders, profile } = options
213 const input = rtmpUrl
215 const command = getFFmpeg(input)
216 command.inputOption('-fflags nobuffer')
218 const varStreamMap: string[] = []
220 command.complexFilter([
224 options: resolutions.length,
225 outputs: resolutions.map(r => `vtemp${r}`)
228 ...resolutions.map(r => ({
231 options: `w=-2:h=${r}`,
236 command.outputOption('-preset superfast')
238 for (let i = 0; i < resolutions.length; i++) {
239 const resolution = resolutions[i]
240 const baseEncoderBuilderParams = { input, availableEncoders, profile, fps, resolution, streamNum: i, videoType: 'live' as 'live' }
243 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' }))
244 if (!builderResult) {
245 throw new Error('No available live video encoder found')
248 command.outputOption(`-map [vout${resolution}]`)
250 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps, streamNum: i })
252 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
254 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
255 command.addOutputOptions(builderResult.result.outputOptions)
259 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' }))
260 if (!builderResult) {
261 throw new Error('No available live audio encoder found')
264 command.outputOption('-map a:0')
266 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps, streamNum: i })
268 logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult)
270 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
271 command.addOutputOptions(builderResult.result.outputOptions)
274 varStreamMap.push(`v:${i},a:${i}`)
277 addDefaultLiveHLSParams(command, outPath, deleteSegments)
279 command.outputOption('-var_stream_map', varStreamMap.join(' '))
284 function getLiveMuxingCommand (rtmpUrl: string, outPath: string, deleteSegments: boolean) {
285 const command = getFFmpeg(rtmpUrl)
286 command.inputOption('-fflags nobuffer')
288 command.outputOption('-c:v copy')
289 command.outputOption('-c:a copy')
290 command.outputOption('-map 0:a?')
291 command.outputOption('-map 0:v?')
293 addDefaultLiveHLSParams(command, outPath, deleteSegments)
298 async function hlsPlaylistToFragmentedMP4 (hlsDirectory: string, segmentFiles: string[], outputPath: string) {
299 const concatFilePath = join(hlsDirectory, 'concat.txt')
301 function cleaner () {
302 remove(concatFilePath)
303 .catch(err => logger.error('Cannot remove concat file in %s.', hlsDirectory, { err }))
306 // First concat the ts files to a mp4 file
307 const content = segmentFiles.map(f => 'file ' + f)
310 await writeFile(concatFilePath, content + '\n')
312 const command = getFFmpeg(concatFilePath)
313 command.inputOption('-safe 0')
314 command.inputOption('-f concat')
316 command.outputOption('-c:v copy')
317 command.audioFilter('aresample=async=1:first_pts=0')
318 command.output(outputPath)
320 return runCommand(command, cleaner)
323 function buildStreamSuffix (base: string, streamNum?: number) {
324 if (streamNum !== undefined) {
325 return `${base}:${streamNum}`
331 // ---------------------------------------------------------------------------
334 getLiveTranscodingCommand,
335 getLiveMuxingCommand,
339 generateImageFromVideoFile,
341 TranscodeOptionsType,
343 hlsPlaylistToFragmentedMP4
346 // ---------------------------------------------------------------------------
348 // ---------------------------------------------------------------------------
350 // ---------------------------------------------------------------------------
352 function addDefaultEncoderParams (options: {
353 command: ffmpeg.FfmpegCommand
354 encoder: 'libx264' | string
358 const { command, encoder, fps, streamNum } = options
360 if (encoder === 'libx264') {
361 // 3.1 is the minimal resource allocation for our highest supported resolution
362 command.outputOption('-level 3.1')
363 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
364 .outputOption('-b_strategy 1')
365 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
366 .outputOption('-bf 16')
367 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
368 .outputOption(buildStreamSuffix('-pix_fmt', streamNum) + ' yuv420p')
369 // strip all metadata
370 .outputOption('-map_metadata -1')
371 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
372 .outputOption(buildStreamSuffix('-max_muxing_queue_size', streamNum) + ' 1024')
375 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
376 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
377 // https://superuser.com/a/908325
378 command.outputOption('-g ' + (fps * 2))
383 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, deleteSegments: boolean) {
384 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
385 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
387 if (deleteSegments === true) {
388 command.outputOption('-hls_flags delete_segments')
391 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
392 command.outputOption('-master_pl_name master.m3u8')
393 command.outputOption(`-f hls`)
395 command.output(join(outPath, '%v.m3u8'))
398 // ---------------------------------------------------------------------------
399 // Transcode VOD command builders
400 // ---------------------------------------------------------------------------
402 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
403 let fps = await getVideoFileFPS(options.inputPath)
405 // On small/medium resolutions, limit FPS
406 options.resolution !== undefined &&
407 options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
408 fps > VIDEO_TRANSCODING_FPS.AVERAGE
410 // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
411 fps = getClosestFramerateStandard(fps, 'STANDARD')
414 command = await presetVideo(command, options.inputPath, options, fps)
416 if (options.resolution !== undefined) {
417 // '?x720' or '720x?' for example
418 const size = options.isPortraitMode === true
419 ? `${options.resolution}x?`
420 : `?x${options.resolution}`
422 command = command.size(size)
426 if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
427 else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
429 command = command.withFPS(fps)
434 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
435 command = command.loop(undefined)
437 command = await presetVideo(command, options.audioPath, options)
440 MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
441 Our target situation is closer to a livestream than a stream,
442 since we want to reduce as much a possible the encoding burden,
443 although not to the point of a livestream where there is a hard
444 constraint on the frames per second to be encoded.
446 command.outputOption('-preset:v veryfast')
448 command = command.input(options.audioPath)
449 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
450 .outputOption('-tune stillimage')
451 .outputOption('-shortest')
456 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
457 command = presetOnlyAudio(command)
462 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
463 command = presetCopy(command)
465 command = command.outputOption('-map_metadata -1') // strip all metadata
466 .outputOption('-movflags faststart')
471 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
472 const videoPath = getHLSVideoPath(options)
474 if (options.copyCodecs) command = presetCopy(command)
475 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
476 else command = await buildx264VODCommand(command, options)
478 command = command.outputOption('-hls_time 4')
479 .outputOption('-hls_list_size 0')
480 .outputOption('-hls_playlist_type vod')
481 .outputOption('-hls_segment_filename ' + videoPath)
482 .outputOption('-hls_segment_type fmp4')
483 .outputOption('-f hls')
484 .outputOption('-hls_flags single_file')
489 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
490 if (options.type !== 'hls') return
492 const fileContent = await readFile(options.outputPath)
494 const videoFileName = options.hlsPlaylist.videoFilename
495 const videoFilePath = getHLSVideoPath(options)
497 // Fix wrong mapping with some ffmpeg versions
498 const newContent = fileContent.toString()
499 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
501 await writeFile(options.outputPath, newContent)
504 function getHLSVideoPath (options: HLSTranscodeOptions) {
505 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
508 // ---------------------------------------------------------------------------
509 // Transcoding presets
510 // ---------------------------------------------------------------------------
512 async function getEncoderBuilderResult (options: {
516 availableEncoders: AvailableEncoders
519 videoType: 'vod' | 'live'
525 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
527 const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType]
529 for (const encoder of encodersToTry) {
530 if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue
532 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder]
533 let builder = builderProfiles[profile]
536 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
537 builder = builderProfiles.default
540 const result = await builder({ input, resolution: resolution, fps, streamNum })
545 // If we don't have output options, then copy the input stream
546 encoder: result.copy === true
555 async function presetVideo (
556 command: ffmpeg.FfmpegCommand,
558 transcodeOptions: TranscodeOptions,
561 let localCommand = command
563 .outputOption('-movflags faststart')
566 const parsedAudio = await getAudioStream(input)
568 let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
570 if (!parsedAudio.audioStream) {
571 localCommand = localCommand.noAudio()
572 streamsToProcess = [ 'VIDEO' ]
575 for (const streamType of streamsToProcess) {
576 const { profile, resolution, availableEncoders } = transcodeOptions
578 const builderResult = await getEncoderBuilderResult({
585 videoType: 'vod' as 'vod'
588 if (!builderResult) {
589 throw new Error('No available encoder found for stream ' + streamType)
592 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
594 if (streamType === 'VIDEO') {
595 localCommand.videoCodec(builderResult.encoder)
596 } else if (streamType === 'AUDIO') {
597 localCommand.audioCodec(builderResult.encoder)
600 command.addOutputOptions(builderResult.result.outputOptions)
601 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
607 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
614 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
621 // ---------------------------------------------------------------------------
623 // ---------------------------------------------------------------------------
625 function getFFmpeg (input: string) {
626 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
627 const command = ffmpeg(input, { niceness: FFMPEG_NICE.TRANSCODING, cwd: CONFIG.STORAGE.TMP_DIR })
629 if (CONFIG.TRANSCODING.THREADS > 0) {
630 // If we don't set any threads ffmpeg will chose automatically
631 command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
637 async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
638 return new Promise<void>((res, rej) => {
639 command.on('error', (err, stdout, stderr) => {
642 logger.error('Error in transcoding job.', { stdout, stderr })
646 command.on('end', () => {