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, VIDEO_TRANSCODING_ENCODERS } 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 = {
49 [ id in 'live' | 'vod' ]: {
50 [ encoder in 'libx264' | 'aac' | 'libfdk_aac' ]?: EncoderProfile<EncoderOptionsBuilder>
54 // ---------------------------------------------------------------------------
56 // ---------------------------------------------------------------------------
58 function convertWebPToJPG (path: string, destination: string): Promise<void> {
59 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
62 return runCommand(command)
68 newSize: { width: number, height: number }
70 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
72 .size(`${newSize.width}x${newSize.height}`)
75 return runCommand(command)
78 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
79 const pendingImageName = 'pending-' + imageName
82 filename: pendingImageName,
87 const pendingImagePath = join(folder, pendingImageName)
90 await new Promise<string>((res, rej) => {
91 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
93 .on('end', () => res(imageName))
97 const destination = join(folder, imageName)
98 await processImage(pendingImagePath, destination, size)
100 logger.error('Cannot generate image from video %s.', fromPath, { err })
103 await remove(pendingImagePath)
105 logger.debug('Cannot remove pending image path after generation error.', { err })
110 // ---------------------------------------------------------------------------
111 // Transcode meta function
112 // ---------------------------------------------------------------------------
114 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
116 interface BaseTranscodeOptions {
117 type: TranscodeOptionsType
122 availableEncoders: AvailableEncoders
125 resolution: VideoResolution
127 isPortraitMode?: boolean
132 interface HLSTranscodeOptions extends BaseTranscodeOptions {
136 videoFilename: string
140 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
146 videoFilename: string
150 interface QuickTranscodeOptions extends BaseTranscodeOptions {
151 type: 'quick-transcode'
154 interface VideoTranscodeOptions extends BaseTranscodeOptions {
158 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
163 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
167 type TranscodeOptions =
169 | HLSFromTSTranscodeOptions
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 'hls-from-ts': buildHLSVODFromTSCommand,
181 'merge-audio': buildAudioMergeCommand,
182 'only-audio': buildOnlyAudioCommand,
183 'video': buildx264VODCommand
186 async function transcode (options: TranscodeOptions) {
187 logger.debug('Will run transcode.', { options })
189 let command = getFFmpeg(options.inputPath, 'vod')
190 .output(options.outputPath)
192 command = await builders[options.type](command, options)
194 await runCommand(command, options.job)
196 await fixHLSPlaylistIfNeeded(options)
199 // ---------------------------------------------------------------------------
200 // Live muxing/transcoding functions
201 // ---------------------------------------------------------------------------
203 async function getLiveTranscodingCommand (options: {
206 resolutions: number[]
209 availableEncoders: AvailableEncoders
212 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
213 const input = rtmpUrl
215 const command = getFFmpeg(input, 'live')
217 const varStreamMap: string[] = []
219 command.complexFilter([
223 options: resolutions.length,
224 outputs: resolutions.map(r => `vtemp${r}`)
227 ...resolutions.map(r => ({
230 options: `w=-2:h=${r}`,
235 command.outputOption('-preset superfast')
236 command.outputOption('-sc_threshold 0')
238 addDefaultEncoderGlobalParams({ command })
240 for (let i = 0; i < resolutions.length; i++) {
241 const resolution = resolutions[i]
242 const resolutionFPS = computeFPS(fps, resolution)
244 const baseEncoderBuilderParams = {
251 videoType: 'live' as 'live'
255 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' }))
256 if (!builderResult) {
257 throw new Error('No available live video encoder found')
260 command.outputOption(`-map [vout${resolution}]`)
262 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
264 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
266 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
267 command.addOutputOptions(builderResult.result.outputOptions)
271 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' }))
272 if (!builderResult) {
273 throw new Error('No available live audio encoder found')
276 command.outputOption('-map a:0')
278 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
280 logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult)
282 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
283 command.addOutputOptions(builderResult.result.outputOptions)
286 varStreamMap.push(`v:${i},a:${i}`)
289 addDefaultLiveHLSParams(command, outPath)
291 command.outputOption('-var_stream_map', varStreamMap.join(' '))
296 function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
297 const command = getFFmpeg(rtmpUrl, 'live')
299 command.outputOption('-c:v copy')
300 command.outputOption('-c:a copy')
301 command.outputOption('-map 0:a?')
302 command.outputOption('-map 0:v?')
304 addDefaultLiveHLSParams(command, outPath)
309 function buildStreamSuffix (base: string, streamNum?: number) {
310 if (streamNum !== undefined) {
311 return `${base}:${streamNum}`
317 // ---------------------------------------------------------------------------
319 // ---------------------------------------------------------------------------
321 function addDefaultEncoderGlobalParams (options: {
322 command: ffmpeg.FfmpegCommand
324 const { command } = options
326 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
327 command.outputOption('-max_muxing_queue_size 1024')
328 // strip all metadata
329 .outputOption('-map_metadata -1')
330 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
331 .outputOption('-b_strategy 1')
332 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
333 .outputOption('-bf 16')
334 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
335 .outputOption('-pix_fmt yuv420p')
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(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
351 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
352 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
353 // https://superuser.com/a/908325
354 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
359 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
360 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
361 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
362 command.outputOption('-hls_flags delete_segments+independent_segments')
363 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
364 command.outputOption('-master_pl_name master.m3u8')
365 command.outputOption(`-f hls`)
367 command.output(join(outPath, '%v.m3u8'))
370 // ---------------------------------------------------------------------------
371 // Transcode VOD command builders
372 // ---------------------------------------------------------------------------
374 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
375 let fps = await getVideoFileFPS(options.inputPath)
376 fps = computeFPS(fps, options.resolution)
378 command = await presetVideo(command, options.inputPath, options, fps)
380 if (options.resolution !== undefined) {
381 // '?x720' or '720x?' for example
382 const size = options.isPortraitMode === true
383 ? `${options.resolution}x?`
384 : `?x${options.resolution}`
386 command = command.size(size)
392 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
393 command = command.loop(undefined)
395 command = await presetVideo(command, options.audioPath, options)
397 command.outputOption('-preset:v veryfast')
399 command = command.input(options.audioPath)
400 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
401 .outputOption('-tune stillimage')
402 .outputOption('-shortest')
407 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
408 command = presetOnlyAudio(command)
413 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
414 command = presetCopy(command)
416 command = command.outputOption('-map_metadata -1') // strip all metadata
417 .outputOption('-movflags faststart')
422 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
423 return command.outputOption('-hls_time 4')
424 .outputOption('-hls_list_size 0')
425 .outputOption('-hls_playlist_type vod')
426 .outputOption('-hls_segment_filename ' + outputPath)
427 .outputOption('-hls_segment_type fmp4')
428 .outputOption('-f hls')
429 .outputOption('-hls_flags single_file')
432 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
433 const videoPath = getHLSVideoPath(options)
435 if (options.copyCodecs) command = presetCopy(command)
436 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
437 else command = await buildx264VODCommand(command, options)
439 addCommonHLSVODCommandOptions(command, videoPath)
444 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
445 const videoPath = getHLSVideoPath(options)
447 command.outputOption('-c copy')
450 // Required for example when copying an AAC stream from an MPEG-TS
451 // Since it's a bitstream filter, we don't need to reencode the audio
452 command.outputOption('-bsf:a aac_adtstoasc')
455 addCommonHLSVODCommandOptions(command, videoPath)
460 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
461 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
463 const fileContent = await readFile(options.outputPath)
465 const videoFileName = options.hlsPlaylist.videoFilename
466 const videoFilePath = getHLSVideoPath(options)
468 // Fix wrong mapping with some ffmpeg versions
469 const newContent = fileContent.toString()
470 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
472 await writeFile(options.outputPath, newContent)
475 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
476 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
479 // ---------------------------------------------------------------------------
480 // Transcoding presets
481 // ---------------------------------------------------------------------------
483 async function getEncoderBuilderResult (options: {
487 availableEncoders: AvailableEncoders
490 videoType: 'vod' | 'live'
496 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
498 const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType]
500 for (const encoder of encodersToTry) {
501 if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue
503 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder]
504 let builder = builderProfiles[profile]
507 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
508 builder = builderProfiles.default
511 const result = await builder({ input, resolution: resolution, fps, streamNum })
516 // If we don't have output options, then copy the input stream
517 encoder: result.copy === true
526 async function presetVideo (
527 command: ffmpeg.FfmpegCommand,
529 transcodeOptions: TranscodeOptions,
532 let localCommand = command
534 .outputOption('-movflags faststart')
536 addDefaultEncoderGlobalParams({ command })
539 const parsedAudio = await getAudioStream(input)
541 let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
543 if (!parsedAudio.audioStream) {
544 localCommand = localCommand.noAudio()
545 streamsToProcess = [ 'VIDEO' ]
548 for (const streamType of streamsToProcess) {
549 const { profile, resolution, availableEncoders } = transcodeOptions
551 const builderResult = await getEncoderBuilderResult({
558 videoType: 'vod' as 'vod'
561 if (!builderResult) {
562 throw new Error('No available encoder found for stream ' + streamType)
565 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
567 if (streamType === 'VIDEO') {
568 localCommand.videoCodec(builderResult.encoder)
569 } else if (streamType === 'AUDIO') {
570 localCommand.audioCodec(builderResult.encoder)
573 command.addOutputOptions(builderResult.result.outputOptions)
574 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
580 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
587 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
594 // ---------------------------------------------------------------------------
596 // ---------------------------------------------------------------------------
598 function getFFmpeg (input: string, type: 'live' | 'vod') {
599 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
600 const command = ffmpeg(input, {
601 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
602 cwd: CONFIG.STORAGE.TMP_DIR
605 const threads = type === 'live'
606 ? CONFIG.LIVE.TRANSCODING.THREADS
607 : CONFIG.TRANSCODING.THREADS
610 // If we don't set any threads ffmpeg will chose automatically
611 command.outputOption('-threads ' + threads)
617 async function runCommand (command: ffmpeg.FfmpegCommand, job?: Job) {
618 return new Promise<void>((res, rej) => {
619 command.on('error', (err, stdout, stderr) => {
620 logger.error('Error in transcoding job.', { stdout, stderr })
624 command.on('end', (stdout, stderr) => {
625 logger.debug('FFmpeg command ended.', { stdout, stderr })
631 command.on('progress', progress => {
632 if (!progress.percent) return
634 job.progress(Math.round(progress.percent))
635 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
643 // ---------------------------------------------------------------------------
646 getLiveTranscodingCommand,
647 getLiveMuxingCommand,
651 generateImageFromVideoFile,
653 TranscodeOptionsType,