1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { VideoResolution } from '../../shared/models/videos'
3 import { CONFIG, MAX_VIDEO_TRANSCODING_FPS } from '../initializers'
4 import { processImage } from './image-utils'
5 import { join } from 'path'
7 async function getVideoFileHeight (path: string) {
8 const videoStream = await getVideoFileStream(path)
9 return videoStream.height
12 async function getVideoFileFPS (path: string) {
13 const videoStream = await getVideoFileStream(path)
15 for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
16 const valuesText: string = videoStream[key]
17 if (!valuesText) continue
19 const [ frames, seconds ] = valuesText.split('/')
20 if (!frames || !seconds) continue
22 const result = parseInt(frames, 10) / parseInt(seconds, 10)
23 if (result > 0) return result
29 function getDurationFromVideoFile (path: string) {
30 return new Promise<number>((res, rej) => {
31 ffmpeg.ffprobe(path, (err, metadata) => {
32 if (err) return rej(err)
34 return res(Math.floor(metadata.format.duration))
39 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
40 const pendingImageName = 'pending-' + imageName
43 filename: pendingImageName,
48 await new Promise<string>((res, rej) => {
51 .on('end', () => res(imageName))
55 const pendingImagePath = join(folder, pendingImageName)
56 const destination = join(folder, imageName)
57 await processImage({ path: pendingImagePath }, destination, size)
60 type TranscodeOptions = {
63 resolution?: VideoResolution
66 function transcode (options: TranscodeOptions) {
67 return new Promise<void>(async (res, rej) => {
68 const fps = await getVideoFileFPS(options.inputPath)
70 let command = ffmpeg(options.inputPath)
71 .output(options.outputPath)
72 .videoCodec('libx264')
73 .outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
74 .outputOption('-movflags faststart')
75 // .outputOption('-crf 18')
77 if (fps > MAX_VIDEO_TRANSCODING_FPS) command = command.withFPS(MAX_VIDEO_TRANSCODING_FPS)
79 if (options.resolution !== undefined) {
80 const size = `?x${options.resolution}` // '?x720' for example
81 command = command.size(size)
84 command.on('error', rej)
90 // ---------------------------------------------------------------------------
94 getDurationFromVideoFile,
95 generateImageFromVideoFile,
100 // ---------------------------------------------------------------------------
102 function getVideoFileStream (path: string) {
103 return new Promise<any>((res, rej) => {
104 ffmpeg.ffprobe(path, (err, metadata) => {
105 if (err) return rej(err)
107 const videoStream = metadata.streams.find(s => s.codec_type === 'video')
108 if (!videoStream) throw new Error('Cannot find video stream of ' + path)
110 return res(videoStream)