+ if (deleteSegments === true) {
+ command.outputOption('-hls_flags delete_segments')
+ }
+
+ command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%04d.ts')}`)
+ command.outputOption('-master_pl_name master.m3u8')
+ command.outputOption(`-f hls`)
+
+ command.output(join(outPath, '%v.m3u8'))
+}
+
+async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
+ let fps = await getVideoFileFPS(options.inputPath)
+ if (
+ // On small/medium resolutions, limit FPS
+ options.resolution !== undefined &&
+ options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN &&
+ fps > VIDEO_TRANSCODING_FPS.AVERAGE
+ ) {
+ // Get closest standard framerate by modulo: downsampling has to be done to a divisor of the nominal fps value
+ fps = getClosestFramerateStandard(fps, 'STANDARD')
+ }
+
+ command = await presetH264(command, options.inputPath, options.resolution, fps)
+
+ if (options.resolution !== undefined) {
+ // '?x720' or '720x?' for example
+ const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}`
+ command = command.size(size)
+ }
+
+ if (fps) {
+ // Hard FPS limits
+ if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = getClosestFramerateStandard(fps, 'HD_STANDARD')
+ else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN
+
+ command = command.withFPS(fps)
+ }
+
+ return command
+}
+
+async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
+ command = command.loop(undefined)
+
+ command = await presetH264VeryFast(command, options.audioPath, options.resolution)
+
+ command = command.input(options.audioPath)
+ .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
+ .outputOption('-tune stillimage')
+ .outputOption('-shortest')
+
+ return command
+}
+
+function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, options: OnlyAudioTranscodeOptions) {
+ command = presetOnlyAudio(command)
+
+ return command
+}
+
+function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
+ command = presetCopy(command)
+
+ command = command.outputOption('-map_metadata -1') // strip all metadata
+ .outputOption('-movflags faststart')
+
+ return command
+}
+
+async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
+ const videoPath = getHLSVideoPath(options)
+
+ if (options.copyCodecs) command = presetCopy(command)
+ else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
+ else command = await buildx264Command(command, options)
+
+ command = command.outputOption('-hls_time 4')
+ .outputOption('-hls_list_size 0')
+ .outputOption('-hls_playlist_type vod')
+ .outputOption('-hls_segment_filename ' + videoPath)
+ .outputOption('-hls_segment_type fmp4')
+ .outputOption('-f hls')
+ .outputOption('-hls_flags single_file')
+
+ return command
+}
+
+function getHLSVideoPath (options: HLSTranscodeOptions) {
+ return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
+}
+
+async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
+ if (options.type !== 'hls') return
+
+ const fileContent = await readFile(options.outputPath)
+
+ const videoFileName = options.hlsPlaylist.videoFilename
+ const videoFilePath = getHLSVideoPath(options)
+
+ // Fix wrong mapping with some ffmpeg versions
+ const newContent = fileContent.toString()
+ .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
+
+ await writeFile(options.outputPath, newContent)
+}
+
+/**
+ * A slightly customised version of the 'veryfast' x264 preset
+ *
+ * The veryfast preset is right in the sweet spot of performance
+ * and quality. Superfast and ultrafast will give you better
+ * performance, but then quality is noticeably worse.
+ */
+async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
+ let localCommand = await presetH264(command, input, resolution, fps)
+
+ localCommand = localCommand.outputOption('-preset:v veryfast')
+
+ /*
+ MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html
+ Our target situation is closer to a livestream than a stream,
+ since we want to reduce as much a possible the encoding burden,
+ although not to the point of a livestream where there is a hard
+ constraint on the frames per second to be encoded.
+ */
+
+ return localCommand
+}
+
+/**
+ * Standard profile, with variable bitrate audio and faststart.
+ *
+ * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel
+ * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr
+ */
+async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) {
+ let localCommand = command
+ .format('mp4')
+ .videoCodec('libx264')
+ .outputOption('-movflags faststart')
+
+ addDefaultX264Params(localCommand)
+
+ const parsedAudio = await audio.get(input)
+
+ if (!parsedAudio.audioStream) {
+ localCommand = localCommand.noAudio()
+ } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available
+ localCommand = localCommand
+ .audioCodec('libfdk_aac')
+ .audioQuality(5)
+ } else {
+ // we try to reduce the ceiling bitrate by making rough matches of bitrates
+ // of course this is far from perfect, but it might save some space in the end
+ localCommand = localCommand.audioCodec('aac')
+
+ const audioCodecName = parsedAudio.audioStream['codec_name']
+
+ if (audio.bitrate[audioCodecName]) {
+ const bitrate = audio.bitrate[audioCodecName](parsedAudio.audioStream['bit_rate'])
+ if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate)
+ }
+ }
+
+ if (fps) {
+ // Constrained Encoding (VBV)
+ // https://slhck.info/video/2017/03/01/rate-control.html
+ // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
+ const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
+ localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ])
+
+ // Keyframe interval of 2 seconds for faster seeking and resolution switching.
+ // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
+ // https://superuser.com/a/908325
+ localCommand = localCommand.outputOption(`-g ${fps * 2}`)
+ }
+
+ return localCommand
+}
+
+function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
+ return command
+ .format('mp4')
+ .videoCodec('copy')
+ .audioCodec('copy')
+}
+
+function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
+ return command
+ .format('mp4')
+ .audioCodec('copy')
+ .noVideo()
+}
+
+function getFFmpeg (input: string) {
+ // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
+ const command = ffmpeg(input, { niceness: FFMPEG_NICE.TRANSCODING, cwd: CONFIG.STORAGE.TMP_DIR })
+
+ if (CONFIG.TRANSCODING.THREADS > 0) {
+ // If we don't set any threads ffmpeg will chose automatically
+ command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
+ }
+
+ return command