Fix lint
[oweals/peertube.git] / server / helpers / ffmpeg-utils.ts
1 import * as ffmpeg from 'fluent-ffmpeg'
2
3 import { CONFIG } from '../initializers'
4 import { VideoResolution } from '../../shared/models/videos/video-resolution.enum'
5
6 function getVideoFileHeight (path: string) {
7   return new Promise<number>((res, rej) => {
8     ffmpeg.ffprobe(path, (err, metadata) => {
9       if (err) return rej(err)
10
11       const videoStream = metadata.streams.find(s => s.codec_type === 'video')
12       return res(videoStream.height)
13     })
14   })
15 }
16
17 function getDurationFromVideoFile (path: string) {
18   return new Promise<number>((res, rej) => {
19     ffmpeg.ffprobe(path, (err, metadata) => {
20       if (err) return rej(err)
21
22       return res(Math.floor(metadata.format.duration))
23     })
24   })
25 }
26
27 function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: string) {
28   const options = {
29     filename: imageName,
30     count: 1,
31     folder
32   }
33
34   if (size !== undefined) {
35     options['size'] = size
36   }
37
38   return new Promise<string>((res, rej) => {
39     ffmpeg(fromPath)
40       .on('error', rej)
41       .on('end', () => res(imageName))
42       .thumbnail(options)
43   })
44 }
45
46 type TranscodeOptions = {
47   inputPath: string
48   outputPath: string
49   resolution?: VideoResolution
50 }
51
52 function transcode (options: TranscodeOptions) {
53   return new Promise<void>((res, rej) => {
54     let command = ffmpeg(options.inputPath)
55                     .output(options.outputPath)
56                     .videoCodec('libx264')
57                     .outputOption('-threads ' + CONFIG.TRANSCODING.THREADS)
58                     .outputOption('-movflags faststart')
59                     // .outputOption('-crf 18')
60
61     if (options.resolution !== undefined) {
62       const size = `?x${options.resolution}` // '?x720' for example
63       command = command.size(size)
64     }
65
66     command.on('error', rej)
67            .on('end', res)
68            .run()
69   })
70 }
71
72 // ---------------------------------------------------------------------------
73
74 export {
75   getVideoFileHeight,
76   getDurationFromVideoFile,
77   generateImageFromVideoFile,
78   transcode
79 }