]>
Commit | Line | Data |
---|---|---|
14d3270f | 1 | import * as ffmpeg from 'fluent-ffmpeg' |
09209296 | 2 | import { dirname, join } from 'path' |
5ba49f26 | 3 | import { getTargetBitrate, getMaxBitrate, VideoResolution } from '../../shared/models/videos' |
6dd9de95 | 4 | import { FFMPEG_NICE, VIDEO_TRANSCODING_FPS } from '../initializers/constants' |
26670720 | 5 | import { processImage } from './image-utils' |
6fdc553a | 6 | import { logger } from './logger' |
e5565833 | 7 | import { checkFFmpegEncoders } from '../initializers/checker-before-init' |
6dd9de95 C |
8 | import { readFile, remove, writeFile } from 'fs-extra' |
9 | import { CONFIG } from '../initializers/config' | |
14d3270f | 10 | |
06215f15 C |
11 | function computeResolutionsToTranscode (videoFileHeight: number) { |
12 | const resolutionsEnabled: number[] = [] | |
13 | const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS | |
14 | ||
15 | // Put in the order we want to proceed jobs | |
16 | const resolutions = [ | |
5c7d6508 | 17 | VideoResolution.H_NOVIDEO, |
06215f15 C |
18 | VideoResolution.H_480P, |
19 | VideoResolution.H_360P, | |
20 | VideoResolution.H_720P, | |
21 | VideoResolution.H_240P, | |
ad3405d0 C |
22 | VideoResolution.H_1080P, |
23 | VideoResolution.H_4K | |
06215f15 C |
24 | ] |
25 | ||
26 | for (const resolution of resolutions) { | |
27 | if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) { | |
28 | resolutionsEnabled.push(resolution) | |
29 | } | |
30 | } | |
31 | ||
32 | return resolutionsEnabled | |
33 | } | |
34 | ||
52201311 | 35 | async function getVideoStreamSize (path: string) { |
5ba49f26 | 36 | const videoStream = await getVideoStreamFromFile(path) |
056aa7f2 | 37 | |
3a149e9f C |
38 | return videoStream === null |
39 | ? { width: 0, height: 0 } | |
40 | : { width: videoStream.width, height: videoStream.height } | |
09209296 C |
41 | } |
42 | ||
52201311 C |
43 | async function getVideoStreamCodec (path: string) { |
44 | const videoStream = await getVideoStreamFromFile(path) | |
45 | ||
46 | if (!videoStream) return '' | |
47 | ||
48 | const videoCodec = videoStream.codec_tag_string | |
49 | ||
50 | const baseProfileMatrix = { | |
51 | 'High': '6400', | |
52 | 'Main': '4D40', | |
53 | 'Baseline': '42E0' | |
54 | } | |
55 | ||
56 | let baseProfile = baseProfileMatrix[videoStream.profile] | |
57 | if (!baseProfile) { | |
58 | logger.warn('Cannot get video profile codec of %s.', path, { videoStream }) | |
59 | baseProfile = baseProfileMatrix['High'] // Fallback | |
60 | } | |
61 | ||
62 | const level = videoStream.level.toString(16) | |
63 | ||
64 | return `${videoCodec}.${baseProfile}${level}` | |
65 | } | |
66 | ||
67 | async function getAudioStreamCodec (path: string) { | |
68 | const { audioStream } = await audio.get(path) | |
69 | ||
70 | if (!audioStream) return '' | |
71 | ||
72 | const audioCodec = audioStream.codec_name | |
49c3bf6f | 73 | if (audioCodec === 'aac') return 'mp4a.40.2' |
52201311 C |
74 | |
75 | logger.warn('Cannot get audio codec of %s.', path, { audioStream }) | |
76 | ||
77 | return 'mp4a.40.2' // Fallback | |
78 | } | |
79 | ||
09209296 | 80 | async function getVideoFileResolution (path: string) { |
52201311 | 81 | const size = await getVideoStreamSize(path) |
09209296 C |
82 | |
83 | return { | |
84 | videoFileResolution: Math.min(size.height, size.width), | |
85 | isPortraitMode: size.height > size.width | |
056aa7f2 | 86 | } |
73c69591 | 87 | } |
14d3270f | 88 | |
73c69591 | 89 | async function getVideoFileFPS (path: string) { |
5ba49f26 | 90 | const videoStream = await getVideoStreamFromFile(path) |
3a149e9f | 91 | if (videoStream === null) return 0 |
5c7d6508 | 92 | |
ef04ae20 | 93 | for (const key of [ 'avg_frame_rate', 'r_frame_rate' ]) { |
3a149e9f | 94 | const valuesText: string = videoStream[ key ] |
73c69591 C |
95 | if (!valuesText) continue |
96 | ||
97 | const [ frames, seconds ] = valuesText.split('/') | |
98 | if (!frames || !seconds) continue | |
99 | ||
100 | const result = parseInt(frames, 10) / parseInt(seconds, 10) | |
3a6f351b | 101 | if (result > 0) return Math.round(result) |
73c69591 C |
102 | } |
103 | ||
104 | return 0 | |
14d3270f C |
105 | } |
106 | ||
edb4ffc7 FA |
107 | async function getVideoFileBitrate (path: string) { |
108 | return new Promise<number>((res, rej) => { | |
109 | ffmpeg.ffprobe(path, (err, metadata) => { | |
110 | if (err) return rej(err) | |
111 | ||
112 | return res(metadata.format.bit_rate) | |
113 | }) | |
114 | }) | |
115 | } | |
116 | ||
14d3270f C |
117 | function getDurationFromVideoFile (path: string) { |
118 | return new Promise<number>((res, rej) => { | |
119 | ffmpeg.ffprobe(path, (err, metadata) => { | |
120 | if (err) return rej(err) | |
121 | ||
122 | return res(Math.floor(metadata.format.duration)) | |
123 | }) | |
124 | }) | |
125 | } | |
126 | ||
26670720 C |
127 | async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) { |
128 | const pendingImageName = 'pending-' + imageName | |
129 | ||
14d3270f | 130 | const options = { |
26670720 | 131 | filename: pendingImageName, |
14d3270f C |
132 | count: 1, |
133 | folder | |
134 | } | |
135 | ||
26670720 | 136 | const pendingImagePath = join(folder, pendingImageName) |
6fdc553a C |
137 | |
138 | try { | |
139 | await new Promise<string>((res, rej) => { | |
7160878c | 140 | ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL }) |
6fdc553a C |
141 | .on('error', rej) |
142 | .on('end', () => res(imageName)) | |
143 | .thumbnail(options) | |
144 | }) | |
145 | ||
146 | const destination = join(folder, imageName) | |
2fb5b3a5 | 147 | await processImage(pendingImagePath, destination, size) |
6fdc553a | 148 | } catch (err) { |
d5b7d911 | 149 | logger.error('Cannot generate image from video %s.', fromPath, { err }) |
6fdc553a C |
150 | |
151 | try { | |
62689b94 | 152 | await remove(pendingImagePath) |
6fdc553a | 153 | } catch (err) { |
d5b7d911 | 154 | logger.debug('Cannot remove pending image path after generation error.', { err }) |
6fdc553a C |
155 | } |
156 | } | |
14d3270f C |
157 | } |
158 | ||
3a149e9f | 159 | type TranscodeOptionsType = 'hls' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio' |
536598cf C |
160 | |
161 | interface BaseTranscodeOptions { | |
162 | type: TranscodeOptionsType | |
14d3270f C |
163 | inputPath: string |
164 | outputPath: string | |
09209296 | 165 | resolution: VideoResolution |
056aa7f2 | 166 | isPortraitMode?: boolean |
536598cf | 167 | } |
09209296 | 168 | |
536598cf C |
169 | interface HLSTranscodeOptions extends BaseTranscodeOptions { |
170 | type: 'hls' | |
d7a25329 | 171 | copyCodecs: boolean |
536598cf | 172 | hlsPlaylist: { |
4c280004 C |
173 | videoFilename: string |
174 | } | |
14d3270f C |
175 | } |
176 | ||
536598cf C |
177 | interface QuickTranscodeOptions extends BaseTranscodeOptions { |
178 | type: 'quick-transcode' | |
179 | } | |
180 | ||
181 | interface VideoTranscodeOptions extends BaseTranscodeOptions { | |
182 | type: 'video' | |
183 | } | |
184 | ||
185 | interface MergeAudioTranscodeOptions extends BaseTranscodeOptions { | |
186 | type: 'merge-audio' | |
187 | audioPath: string | |
188 | } | |
189 | ||
3a149e9f C |
190 | interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions { |
191 | type: 'only-audio' | |
5c7d6508 | 192 | } |
193 | ||
3a149e9f C |
194 | type TranscodeOptions = HLSTranscodeOptions |
195 | | VideoTranscodeOptions | |
196 | | MergeAudioTranscodeOptions | |
197 | | OnlyAudioTranscodeOptions | |
198 | | QuickTranscodeOptions | |
536598cf | 199 | |
14d3270f | 200 | function transcode (options: TranscodeOptions) { |
73c69591 | 201 | return new Promise<void>(async (res, rej) => { |
cdf4cb9e | 202 | try { |
cdf4cb9e C |
203 | let command = ffmpeg(options.inputPath, { niceness: FFMPEG_NICE.TRANSCODING }) |
204 | .output(options.outputPath) | |
14aed608 | 205 | |
536598cf C |
206 | if (options.type === 'quick-transcode') { |
207 | command = await buildQuickTranscodeCommand(command) | |
208 | } else if (options.type === 'hls') { | |
14aed608 | 209 | command = await buildHLSCommand(command, options) |
536598cf C |
210 | } else if (options.type === 'merge-audio') { |
211 | command = await buildAudioMergeCommand(command, options) | |
3a149e9f C |
212 | } else if (options.type === 'only-audio') { |
213 | command = await buildOnlyAudioCommand(command, options) | |
14aed608 C |
214 | } else { |
215 | command = await buildx264Command(command, options) | |
216 | } | |
7160878c | 217 | |
cdf4cb9e C |
218 | if (CONFIG.TRANSCODING.THREADS > 0) { |
219 | // if we don't set any threads ffmpeg will chose automatically | |
220 | command = command.outputOption('-threads ' + CONFIG.TRANSCODING.THREADS) | |
221 | } | |
14d3270f | 222 | |
cdf4cb9e C |
223 | command |
224 | .on('error', (err, stdout, stderr) => { | |
225 | logger.error('Error in transcoding job.', { stdout, stderr }) | |
226 | return rej(err) | |
227 | }) | |
7f8f8bdb | 228 | .on('end', () => { |
536598cf | 229 | return fixHLSPlaylistIfNeeded(options) |
7f8f8bdb C |
230 | .then(() => res()) |
231 | .catch(err => rej(err)) | |
232 | }) | |
cdf4cb9e C |
233 | .run() |
234 | } catch (err) { | |
235 | return rej(err) | |
236 | } | |
14d3270f C |
237 | }) |
238 | } | |
239 | ||
7ed2c1a4 | 240 | async function canDoQuickTranscode (path: string): Promise<boolean> { |
5ba49f26 FA |
241 | // NOTE: This could be optimized by running ffprobe only once (but it runs fast anyway) |
242 | const videoStream = await getVideoStreamFromFile(path) | |
243 | const parsedAudio = await audio.get(path) | |
244 | const fps = await getVideoFileFPS(path) | |
245 | const bitRate = await getVideoFileBitrate(path) | |
246 | const resolution = await getVideoFileResolution(path) | |
247 | ||
248 | // check video params | |
5c7d6508 | 249 | if (videoStream == null) return false |
1600235a | 250 | if (videoStream[ 'codec_name' ] !== 'h264') return false |
f6e0de3f | 251 | if (videoStream[ 'pix_fmt' ] !== 'yuv420p') return false |
1600235a C |
252 | if (fps < VIDEO_TRANSCODING_FPS.MIN || fps > VIDEO_TRANSCODING_FPS.MAX) return false |
253 | if (bitRate > getMaxBitrate(resolution.videoFileResolution, fps, VIDEO_TRANSCODING_FPS)) return false | |
5ba49f26 | 254 | |
3a149e9f | 255 | // check audio params (if audio stream exists) |
5ba49f26 | 256 | if (parsedAudio.audioStream) { |
1600235a C |
257 | if (parsedAudio.audioStream[ 'codec_name' ] !== 'aac') return false |
258 | ||
5ba49f26 | 259 | const maxAudioBitrate = audio.bitrate[ 'aac' ](parsedAudio.audioStream[ 'bit_rate' ]) |
1600235a | 260 | if (maxAudioBitrate !== -1 && parsedAudio.audioStream[ 'bit_rate' ] > maxAudioBitrate) return false |
5ba49f26 | 261 | } |
7ed2c1a4 | 262 | |
5ba49f26 FA |
263 | return true |
264 | } | |
265 | ||
14d3270f C |
266 | // --------------------------------------------------------------------------- |
267 | ||
268 | export { | |
52201311 C |
269 | getVideoStreamCodec, |
270 | getAudioStreamCodec, | |
271 | getVideoStreamSize, | |
056aa7f2 | 272 | getVideoFileResolution, |
14d3270f C |
273 | getDurationFromVideoFile, |
274 | generateImageFromVideoFile, | |
536598cf C |
275 | TranscodeOptions, |
276 | TranscodeOptionsType, | |
73c69591 | 277 | transcode, |
7160878c | 278 | getVideoFileFPS, |
06215f15 | 279 | computeResolutionsToTranscode, |
edb4ffc7 | 280 | audio, |
5ba49f26 FA |
281 | getVideoFileBitrate, |
282 | canDoQuickTranscode | |
73c69591 C |
283 | } |
284 | ||
285 | // --------------------------------------------------------------------------- | |
286 | ||
d7a25329 | 287 | async function buildx264Command (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) { |
14aed608 C |
288 | let fps = await getVideoFileFPS(options.inputPath) |
289 | // On small/medium resolutions, limit FPS | |
290 | if ( | |
291 | options.resolution !== undefined && | |
292 | options.resolution < VIDEO_TRANSCODING_FPS.KEEP_ORIGIN_FPS_RESOLUTION_MIN && | |
293 | fps > VIDEO_TRANSCODING_FPS.AVERAGE | |
294 | ) { | |
295 | fps = VIDEO_TRANSCODING_FPS.AVERAGE | |
296 | } | |
297 | ||
536598cf | 298 | command = await presetH264(command, options.inputPath, options.resolution, fps) |
14aed608 C |
299 | |
300 | if (options.resolution !== undefined) { | |
301 | // '?x720' or '720x?' for example | |
302 | const size = options.isPortraitMode === true ? `${options.resolution}x?` : `?x${options.resolution}` | |
303 | command = command.size(size) | |
304 | } | |
305 | ||
306 | if (fps) { | |
307 | // Hard FPS limits | |
308 | if (fps > VIDEO_TRANSCODING_FPS.MAX) fps = VIDEO_TRANSCODING_FPS.MAX | |
309 | else if (fps < VIDEO_TRANSCODING_FPS.MIN) fps = VIDEO_TRANSCODING_FPS.MIN | |
310 | ||
311 | command = command.withFPS(fps) | |
312 | } | |
313 | ||
314 | return command | |
315 | } | |
316 | ||
536598cf C |
317 | async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) { |
318 | command = command.loop(undefined) | |
319 | ||
320 | command = await presetH264VeryFast(command, options.audioPath, options.resolution) | |
321 | ||
322 | command = command.input(options.audioPath) | |
323 | .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error | |
324 | .outputOption('-tune stillimage') | |
325 | .outputOption('-shortest') | |
326 | ||
327 | return command | |
328 | } | |
329 | ||
3a149e9f C |
330 | async function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, options: OnlyAudioTranscodeOptions) { |
331 | command = await presetOnlyAudio(command) | |
5c7d6508 | 332 | |
333 | return command | |
334 | } | |
335 | ||
536598cf C |
336 | async function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) { |
337 | command = await presetCopy(command) | |
338 | ||
339 | command = command.outputOption('-map_metadata -1') // strip all metadata | |
340 | .outputOption('-movflags faststart') | |
341 | ||
342 | return command | |
343 | } | |
344 | ||
345 | async function buildHLSCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) { | |
14aed608 C |
346 | const videoPath = getHLSVideoPath(options) |
347 | ||
d7a25329 C |
348 | if (options.copyCodecs) command = await presetCopy(command) |
349 | else command = await buildx264Command(command, options) | |
14aed608 C |
350 | |
351 | command = command.outputOption('-hls_time 4') | |
352 | .outputOption('-hls_list_size 0') | |
353 | .outputOption('-hls_playlist_type vod') | |
354 | .outputOption('-hls_segment_filename ' + videoPath) | |
355 | .outputOption('-hls_segment_type fmp4') | |
356 | .outputOption('-f hls') | |
357 | .outputOption('-hls_flags single_file') | |
358 | ||
359 | return command | |
360 | } | |
361 | ||
536598cf | 362 | function getHLSVideoPath (options: HLSTranscodeOptions) { |
7f8f8bdb C |
363 | return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}` |
364 | } | |
365 | ||
536598cf C |
366 | async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) { |
367 | if (options.type !== 'hls') return | |
7f8f8bdb | 368 | |
7f8f8bdb C |
369 | const fileContent = await readFile(options.outputPath) |
370 | ||
371 | const videoFileName = options.hlsPlaylist.videoFilename | |
372 | const videoFilePath = getHLSVideoPath(options) | |
373 | ||
536598cf | 374 | // Fix wrong mapping with some ffmpeg versions |
7f8f8bdb C |
375 | const newContent = fileContent.toString() |
376 | .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`) | |
377 | ||
378 | await writeFile(options.outputPath, newContent) | |
379 | } | |
380 | ||
5ba49f26 | 381 | function getVideoStreamFromFile (path: string) { |
73c69591 C |
382 | return new Promise<any>((res, rej) => { |
383 | ffmpeg.ffprobe(path, (err, metadata) => { | |
384 | if (err) return rej(err) | |
385 | ||
386 | const videoStream = metadata.streams.find(s => s.codec_type === 'video') | |
3a149e9f | 387 | return res(videoStream || null) |
73c69591 C |
388 | }) |
389 | }) | |
14d3270f | 390 | } |
4176e227 RK |
391 | |
392 | /** | |
393 | * A slightly customised version of the 'veryfast' x264 preset | |
394 | * | |
395 | * The veryfast preset is right in the sweet spot of performance | |
396 | * and quality. Superfast and ultrafast will give you better | |
397 | * performance, but then quality is noticeably worse. | |
398 | */ | |
536598cf C |
399 | async function presetH264VeryFast (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) { |
400 | let localCommand = await presetH264(command, input, resolution, fps) | |
401 | ||
cdf4cb9e | 402 | localCommand = localCommand.outputOption('-preset:v veryfast') |
536598cf | 403 | |
4176e227 RK |
404 | /* |
405 | MAIN reference: https://slhck.info/video/2017/03/01/rate-control.html | |
406 | Our target situation is closer to a livestream than a stream, | |
407 | since we want to reduce as much a possible the encoding burden, | |
536598cf | 408 | although not to the point of a livestream where there is a hard |
4176e227 | 409 | constraint on the frames per second to be encoded. |
4176e227 | 410 | */ |
cdf4cb9e C |
411 | |
412 | return localCommand | |
4176e227 RK |
413 | } |
414 | ||
4176e227 RK |
415 | /** |
416 | * A toolbox to play with audio | |
417 | */ | |
418 | namespace audio { | |
3a149e9f | 419 | export const get = (videoPath: string) => { |
4176e227 RK |
420 | // without position, ffprobe considers the last input only |
421 | // we make it consider the first input only | |
4a5ccac5 | 422 | // if you pass a file path to pos, then ffprobe acts on that file directly |
7160878c | 423 | return new Promise<{ absolutePath: string, audioStream?: any }>((res, rej) => { |
cdf4cb9e C |
424 | |
425 | function parseFfprobe (err: any, data: ffmpeg.FfprobeData) { | |
7160878c RK |
426 | if (err) return rej(err) |
427 | ||
428 | if ('streams' in data) { | |
3a149e9f | 429 | const audioStream = data.streams.find(stream => stream[ 'codec_type' ] === 'audio') |
7160878c RK |
430 | if (audioStream) { |
431 | return res({ | |
432 | absolutePath: data.format.filename, | |
433 | audioStream | |
434 | }) | |
4a5ccac5 | 435 | } |
7160878c | 436 | } |
cdf4cb9e | 437 | |
7160878c | 438 | return res({ absolutePath: data.format.filename }) |
cdf4cb9e C |
439 | } |
440 | ||
3a149e9f | 441 | return ffmpeg.ffprobe(videoPath, parseFfprobe) |
4a5ccac5 | 442 | }) |
4176e227 RK |
443 | } |
444 | ||
445 | export namespace bitrate { | |
eed24d26 | 446 | const baseKbitrate = 384 |
4176e227 | 447 | |
9b474844 | 448 | const toBits = (kbits: number) => kbits * 8000 |
4176e227 RK |
449 | |
450 | export const aac = (bitrate: number): number => { | |
451 | switch (true) { | |
9b474844 C |
452 | case bitrate > toBits(baseKbitrate): |
453 | return baseKbitrate | |
454 | ||
455 | default: | |
456 | return -1 // we interpret it as a signal to copy the audio stream as is | |
4176e227 RK |
457 | } |
458 | } | |
459 | ||
460 | export const mp3 = (bitrate: number): number => { | |
7160878c RK |
461 | /* |
462 | a 192kbit/sec mp3 doesn't hold as much information as a 192kbit/sec aac. | |
463 | That's why, when using aac, we can go to lower kbit/sec. The equivalences | |
464 | made here are not made to be accurate, especially with good mp3 encoders. | |
465 | */ | |
4176e227 | 466 | switch (true) { |
9b474844 C |
467 | case bitrate <= toBits(192): |
468 | return 128 | |
469 | ||
470 | case bitrate <= toBits(384): | |
471 | return 256 | |
472 | ||
473 | default: | |
474 | return baseKbitrate | |
4176e227 RK |
475 | } |
476 | } | |
477 | } | |
478 | } | |
479 | ||
480 | /** | |
481 | * Standard profile, with variable bitrate audio and faststart. | |
482 | * | |
483 | * As for the audio, quality '5' is the highest and ensures 96-112kbps/channel | |
484 | * See https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_vbr | |
485 | */ | |
536598cf | 486 | async function presetH264 (command: ffmpeg.FfmpegCommand, input: string, resolution: VideoResolution, fps?: number) { |
cdf4cb9e | 487 | let localCommand = command |
4176e227 RK |
488 | .format('mp4') |
489 | .videoCodec('libx264') | |
52201311 C |
490 | .outputOption('-level 3.1') // 3.1 is the minimal resource allocation for our highest supported resolution |
491 | .outputOption('-b_strategy 1') // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it | |
4176e227 | 492 | .outputOption('-bf 16') // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16 |
408f50eb | 493 | .outputOption('-pix_fmt yuv420p') // allows import of source material with incompatible pixel formats (e.g. MJPEG video) |
4a5ccac5 | 494 | .outputOption('-map_metadata -1') // strip all metadata |
4176e227 | 495 | .outputOption('-movflags faststart') |
4176e227 | 496 | |
536598cf | 497 | const parsedAudio = await audio.get(input) |
4176e227 | 498 | |
cdf4cb9e C |
499 | if (!parsedAudio.audioStream) { |
500 | localCommand = localCommand.noAudio() | |
501 | } else if ((await checkFFmpegEncoders()).get('libfdk_aac')) { // we favor VBR, if a good AAC encoder is available | |
502 | localCommand = localCommand | |
4176e227 RK |
503 | .audioCodec('libfdk_aac') |
504 | .audioQuality(5) | |
cdf4cb9e | 505 | } else { |
536598cf | 506 | // we try to reduce the ceiling bitrate by making rough matches of bitrates |
cdf4cb9e | 507 | // of course this is far from perfect, but it might save some space in the end |
536598cf C |
508 | localCommand = localCommand.audioCodec('aac') |
509 | ||
cdf4cb9e | 510 | const audioCodecName = parsedAudio.audioStream[ 'codec_name' ] |
cdf4cb9e | 511 | |
536598cf C |
512 | if (audio.bitrate[ audioCodecName ]) { |
513 | const bitrate = audio.bitrate[ audioCodecName ](parsedAudio.audioStream[ 'bit_rate' ]) | |
64e3e270 | 514 | if (bitrate !== undefined && bitrate !== -1) localCommand = localCommand.audioBitrate(bitrate) |
cdf4cb9e | 515 | } |
4176e227 RK |
516 | } |
517 | ||
536598cf C |
518 | if (fps) { |
519 | // Constrained Encoding (VBV) | |
520 | // https://slhck.info/video/2017/03/01/rate-control.html | |
521 | // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate | |
522 | const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS) | |
523 | localCommand = localCommand.outputOptions([ `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}` ]) | |
524 | ||
525 | // Keyframe interval of 2 seconds for faster seeking and resolution switching. | |
526 | // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html | |
527 | // https://superuser.com/a/908325 | |
528 | localCommand = localCommand.outputOption(`-g ${fps * 2}`) | |
529 | } | |
bcf21a37 | 530 | |
cdf4cb9e | 531 | return localCommand |
4176e227 | 532 | } |
14aed608 C |
533 | |
534 | async function presetCopy (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> { | |
535 | return command | |
536 | .format('mp4') | |
537 | .videoCodec('copy') | |
538 | .audioCodec('copy') | |
539 | } | |
5c7d6508 | 540 | |
3a149e9f | 541 | async function presetOnlyAudio (command: ffmpeg.FfmpegCommand): Promise<ffmpeg.FfmpegCommand> { |
5c7d6508 | 542 | return command |
543 | .format('mp4') | |
544 | .audioCodec('copy') | |
545 | .noVideo() | |
546 | } |