Keep ratio for thumbnails
[oweals/peertube.git] / server / helpers / ffmpeg-utils.ts
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'
6
7 async function getVideoFileHeight (path: string) {
8   const videoStream = await getVideoFileStream(path)
9   return videoStream.height
10 }
11
12 async function getVideoFileFPS (path: string) {
13   const videoStream = await getVideoFileStream(path)
14
15   for (const key of [ 'r_frame_rate' , 'avg_frame_rate' ]) {
16     const valuesText: string = videoStream[key]
17     if (!valuesText) continue
18
19     const [ frames, seconds ] = valuesText.split('/')
20     if (!frames || !seconds) continue
21
22     const result = parseInt(frames, 10) / parseInt(seconds, 10)
23     if (result > 0) return result
24   }
25
26   return 0
27 }
28
29 function getDurationFromVideoFile (path: string) {
30   return new Promise<number>((res, rej) => {
31     ffmpeg.ffprobe(path, (err, metadata) => {
32       if (err) return rej(err)
33
34       return res(Math.floor(metadata.format.duration))
35     })
36   })
37 }
38
39 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
40   const pendingImageName = 'pending-' + imageName
41
42   const options = {
43     filename: pendingImageName,
44     count: 1,
45     folder
46   }
47
48   await new Promise<string>((res, rej) => {
49     ffmpeg(fromPath)
50       .on('error', rej)
51       .on('end', () => res(imageName))
52       .thumbnail(options)
53   })
54
55   const pendingImagePath = join(folder, pendingImageName)
56   const destination = join(folder, imageName)
57   await processImage({ path: pendingImagePath }, destination, size)
58 }
59
60 type TranscodeOptions = {
61   inputPath: string
62   outputPath: string
63   resolution?: VideoResolution
64 }
65
66 function transcode (options: TranscodeOptions) {
67   return new Promise<void>(async (res, rej) => {
68     const fps = await getVideoFileFPS(options.inputPath)
69
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')
76
77     if (fps > MAX_VIDEO_TRANSCODING_FPS) command = command.withFPS(MAX_VIDEO_TRANSCODING_FPS)
78
79     if (options.resolution !== undefined) {
80       const size = `?x${options.resolution}` // '?x720' for example
81       command = command.size(size)
82     }
83
84     command.on('error', rej)
85            .on('end', res)
86            .run()
87   })
88 }
89
90 // ---------------------------------------------------------------------------
91
92 export {
93   getVideoFileHeight,
94   getDurationFromVideoFile,
95   generateImageFromVideoFile,
96   transcode,
97   getVideoFileFPS
98 }
99
100 // ---------------------------------------------------------------------------
101
102 function getVideoFileStream (path: string) {
103   return new Promise<any>((res, rej) => {
104     ffmpeg.ffprobe(path, (err, metadata) => {
105       if (err) return rej(err)
106
107       const videoStream = metadata.streams.find(s => s.codec_type === 'video')
108       if (!videoStream) throw new Error('Cannot find video stream of ' + path)
109
110       return res(videoStream)
111     })
112   })
113 }