]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/ffprobe.ts
Fix audio file merge
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / ffprobe.ts
1 import { ffprobe, FfprobeData } from 'fluent-ffmpeg'
2 import { VideoFileMetadata } from '@shared/models/videos'
3
4 /**
5 *
6 * Helpers to run ffprobe and extract data from the JSON output
7 *
8 */
9
10 function ffprobePromise (path: string) {
11 return new Promise<FfprobeData>((res, rej) => {
12 ffprobe(path, (err, data) => {
13 if (err) return rej(err)
14
15 return res(data)
16 })
17 })
18 }
19
20 // ---------------------------------------------------------------------------
21 // Audio
22 // ---------------------------------------------------------------------------
23
24 const imageCodecs = new Set([
25 'ansi', 'apng', 'bintext', 'bmp', 'brender_pix', 'dpx', 'exr', 'fits', 'gem', 'gif', 'jpeg2000', 'jpgls', 'mjpeg', 'mjpegb', 'msp2',
26 'pam', 'pbm', 'pcx', 'pfm', 'pgm', 'pgmyuv', 'pgx', 'photocd', 'pictor', 'png', 'ppm', 'psd', 'sgi', 'sunrast', 'svg', 'targa', 'tiff',
27 'txd', 'webp', 'xbin', 'xbm', 'xface', 'xpm', 'xwd'
28 ])
29
30 async function isAudioFile (path: string, existingProbe?: FfprobeData) {
31 const videoStream = await getVideoStream(path, existingProbe)
32 if (!videoStream) return true
33
34 if (imageCodecs.has(videoStream.codec_name)) return true
35
36 return false
37 }
38
39 async function hasAudioStream (path: string, existingProbe?: FfprobeData) {
40 const { audioStream } = await getAudioStream(path, existingProbe)
41
42 return !!audioStream
43 }
44
45 async function getAudioStream (videoPath: string, existingProbe?: FfprobeData) {
46 // without position, ffprobe considers the last input only
47 // we make it consider the first input only
48 // if you pass a file path to pos, then ffprobe acts on that file directly
49 const data = existingProbe || await ffprobePromise(videoPath)
50
51 if (Array.isArray(data.streams)) {
52 const audioStream = data.streams.find(stream => stream['codec_type'] === 'audio')
53
54 if (audioStream) {
55 return {
56 absolutePath: data.format.filename,
57 audioStream,
58 bitrate: parseInt(audioStream['bit_rate'] + '', 10)
59 }
60 }
61 }
62
63 return { absolutePath: data.format.filename }
64 }
65
66 function getMaxAudioBitrate (type: 'aac' | 'mp3' | string, bitrate: number) {
67 const maxKBitrate = 384
68 const kToBits = (kbits: number) => kbits * 1000
69
70 // If we did not manage to get the bitrate, use an average value
71 if (!bitrate) return 256
72
73 if (type === 'aac') {
74 switch (true) {
75 case bitrate > kToBits(maxKBitrate):
76 return maxKBitrate
77
78 default:
79 return -1 // we interpret it as a signal to copy the audio stream as is
80 }
81 }
82
83 /*
84 a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac.
85 That's why, when using aac, we can go to lower kbit/sec. The equivalences
86 made here are not made to be accurate, especially with good mp3 encoders.
87 */
88 switch (true) {
89 case bitrate <= kToBits(192):
90 return 128
91
92 case bitrate <= kToBits(384):
93 return 256
94
95 default:
96 return maxKBitrate
97 }
98 }
99
100 // ---------------------------------------------------------------------------
101 // Video
102 // ---------------------------------------------------------------------------
103
104 async function getVideoStreamDimensionsInfo (path: string, existingProbe?: FfprobeData) {
105 const videoStream = await getVideoStream(path, existingProbe)
106 if (!videoStream) return undefined
107
108 return {
109 width: videoStream.width,
110 height: videoStream.height,
111 ratio: Math.max(videoStream.height, videoStream.width) / Math.min(videoStream.height, videoStream.width),
112 resolution: Math.min(videoStream.height, videoStream.width),
113 isPortraitMode: videoStream.height > videoStream.width
114 }
115 }
116
117 async function getVideoStreamFPS (path: string, existingProbe?: FfprobeData) {
118 const videoStream = await getVideoStream(path, existingProbe)
119 if (!videoStream) return 0
120
121 for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) {
122 const valuesText: string = videoStream[key]
123 if (!valuesText) continue
124
125 const [ frames, seconds ] = valuesText.split('/')
126 if (!frames || !seconds) continue
127
128 const result = parseInt(frames, 10) / parseInt(seconds, 10)
129 if (result > 0) return Math.round(result)
130 }
131
132 return 0
133 }
134
135 async function buildFileMetadata (path: string, existingProbe?: FfprobeData) {
136 const metadata = existingProbe || await ffprobePromise(path)
137
138 return new VideoFileMetadata(metadata)
139 }
140
141 async function getVideoStreamBitrate (path: string, existingProbe?: FfprobeData): Promise<number> {
142 const metadata = await buildFileMetadata(path, existingProbe)
143
144 let bitrate = metadata.format.bit_rate as number
145 if (bitrate && !isNaN(bitrate)) return bitrate
146
147 const videoStream = await getVideoStream(path, existingProbe)
148 if (!videoStream) return undefined
149
150 bitrate = videoStream?.bit_rate
151 if (bitrate && !isNaN(bitrate)) return bitrate
152
153 return undefined
154 }
155
156 async function getVideoStreamDuration (path: string, existingProbe?: FfprobeData) {
157 const metadata = await buildFileMetadata(path, existingProbe)
158
159 return Math.round(metadata.format.duration)
160 }
161
162 async function getVideoStream (path: string, existingProbe?: FfprobeData) {
163 const metadata = await buildFileMetadata(path, existingProbe)
164
165 return metadata.streams.find(s => s.codec_type === 'video')
166 }
167
168 // ---------------------------------------------------------------------------
169
170 export {
171 getVideoStreamDimensionsInfo,
172 buildFileMetadata,
173 getMaxAudioBitrate,
174 getVideoStream,
175 getVideoStreamDuration,
176 getAudioStream,
177 getVideoStreamFPS,
178 isAudioFile,
179 ffprobePromise,
180 getVideoStreamBitrate,
181 hasAudioStream
182 }