]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/ffmpeg-utils.ts
Use random names for VOD HLS playlists
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
CommitLineData
3b01f4c0 1import { Job } from 'bull'
14d3270f 2import * as ffmpeg from 'fluent-ffmpeg'
053aed43 3import { readFile, remove, writeFile } from 'fs-extra'
09209296 4import { dirname, join } from 'path'
529b3752 5import { FFMPEG_NICE, VIDEO_LIVE } from '@server/initializers/constants'
b7c8304c 6import { AvailableEncoders, EncoderOptions, EncoderOptionsBuilder, EncoderProfile, VideoResolution } from '../../shared/models/videos'
c6c0fa6c 7import { CONFIG } from '../initializers/config'
b7c8304c 8import { execPromise, promisify0 } from './core-utils'
884d2c39 9import { computeFPS, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
26670720 10import { processImage } from './image-utils'
6fdc553a 11import { logger } from './logger'
14d3270f 12
6b67897e
C
13/**
14 *
15 * Functions that run transcoding/muxing ffmpeg processes
16 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
17 *
18 */
19
9252a33d
C
20// ---------------------------------------------------------------------------
21// Encoder options
22// ---------------------------------------------------------------------------
23
1896bca0 24type StreamType = 'audio' | 'video'
9252a33d 25
1896bca0
C
26// ---------------------------------------------------------------------------
27// Encoders support
28// ---------------------------------------------------------------------------
9252a33d 29
1896bca0
C
30// Detect supported encoders by ffmpeg
31let supportedEncoders: Map<string, boolean>
32async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
33 if (supportedEncoders !== undefined) {
34 return supportedEncoders
35 }
9252a33d 36
1896bca0
C
37 const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
38 const availableFFmpegEncoders = await getAvailableEncodersPromise()
9252a33d 39
1896bca0
C
40 const searchEncoders = new Set<string>()
41 for (const type of [ 'live', 'vod' ]) {
42 for (const streamType of [ 'audio', 'video' ]) {
43 for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
44 searchEncoders.add(encoder)
45 }
46 }
47 }
9252a33d 48
1896bca0 49 supportedEncoders = new Map<string, boolean>()
9252a33d 50
1896bca0
C
51 for (const searchEncoder of searchEncoders) {
52 supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
529b3752
C
53 }
54
1896bca0 55 logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
529b3752 56
1896bca0 57 return supportedEncoders
9252a33d
C
58}
59
1896bca0
C
60function resetSupportedEncoders () {
61 supportedEncoders = undefined
62}
529b3752 63
9252a33d
C
64// ---------------------------------------------------------------------------
65// Image manipulation
66// ---------------------------------------------------------------------------
67
68function convertWebPToJPG (path: string, destination: string): Promise<void> {
a4a8cd39 69 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
9252a33d
C
70 .output(destination)
71
cd2c3dcd 72 return runCommand({ command, silent: true })
9252a33d
C
73}
74
75function processGIF (
76 path: string,
77 destination: string,
f619de0e 78 newSize: { width: number, height: number }
9252a33d 79): Promise<void> {
a4a8cd39 80 const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
f619de0e
C
81 .fps(20)
82 .size(`${newSize.width}x${newSize.height}`)
83 .output(destination)
9252a33d 84
cd2c3dcd 85 return runCommand({ command })
9252a33d
C
86}
87
26670720
C
88async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
89 const pendingImageName = 'pending-' + imageName
90
14d3270f 91 const options = {
26670720 92 filename: pendingImageName,
14d3270f
C
93 count: 1,
94 folder
95 }
96
26670720 97 const pendingImagePath = join(folder, pendingImageName)
6fdc553a
C
98
99 try {
100 await new Promise<string>((res, rej) => {
7160878c 101 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
6fdc553a
C
102 .on('error', rej)
103 .on('end', () => res(imageName))
104 .thumbnail(options)
105 })
106
107 const destination = join(folder, imageName)
2fb5b3a5 108 await processImage(pendingImagePath, destination, size)
6fdc553a 109 } catch (err) {
d5b7d911 110 logger.error('Cannot generate image from video %s.', fromPath, { err })
6fdc553a
C
111
112 try {
62689b94 113 await remove(pendingImagePath)
6fdc553a 114 } catch (err) {
d5b7d911 115 logger.debug('Cannot remove pending image path after generation error.', { err })
6fdc553a
C
116 }
117 }
14d3270f
C
118}
119
daf6e480
C
120// ---------------------------------------------------------------------------
121// Transcode meta function
122// ---------------------------------------------------------------------------
123
2650d6d4 124type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
536598cf
C
125
126interface BaseTranscodeOptions {
127 type: TranscodeOptionsType
9252a33d 128
14d3270f
C
129 inputPath: string
130 outputPath: string
9252a33d
C
131
132 availableEncoders: AvailableEncoders
133 profile: string
134
318b0bd0 135 resolution: number
9252a33d 136
056aa7f2 137 isPortraitMode?: boolean
3b01f4c0
C
138
139 job?: Job
536598cf 140}
09209296 141
536598cf
C
142interface HLSTranscodeOptions extends BaseTranscodeOptions {
143 type: 'hls'
d7a25329 144 copyCodecs: boolean
536598cf 145 hlsPlaylist: {
4c280004
C
146 videoFilename: string
147 }
14d3270f
C
148}
149
2650d6d4
C
150interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
151 type: 'hls-from-ts'
152
e772bdf1
C
153 isAAC: boolean
154
2650d6d4
C
155 hlsPlaylist: {
156 videoFilename: string
157 }
158}
159
536598cf
C
160interface QuickTranscodeOptions extends BaseTranscodeOptions {
161 type: 'quick-transcode'
162}
163
164interface VideoTranscodeOptions extends BaseTranscodeOptions {
165 type: 'video'
166}
167
168interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
169 type: 'merge-audio'
170 audioPath: string
171}
172
3a149e9f
C
173interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
174 type: 'only-audio'
5c7d6508 175}
176
a1587156
C
177type TranscodeOptions =
178 HLSTranscodeOptions
2650d6d4 179 | HLSFromTSTranscodeOptions
3a149e9f
C
180 | VideoTranscodeOptions
181 | MergeAudioTranscodeOptions
182 | OnlyAudioTranscodeOptions
183 | QuickTranscodeOptions
536598cf 184
daf6e480
C
185const builders: {
186 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
187} = {
188 'quick-transcode': buildQuickTranscodeCommand,
189 'hls': buildHLSVODCommand,
2650d6d4 190 'hls-from-ts': buildHLSVODFromTSCommand,
daf6e480
C
191 'merge-audio': buildAudioMergeCommand,
192 'only-audio': buildOnlyAudioCommand,
9252a33d 193 'video': buildx264VODCommand
daf6e480
C
194}
195
196async function transcode (options: TranscodeOptions) {
9e2b2e76
C
197 logger.debug('Will run transcode.', { options })
198
55223d65 199 let command = getFFmpeg(options.inputPath, 'vod')
daf6e480 200 .output(options.outputPath)
14d3270f 201
daf6e480 202 command = await builders[options.type](command, options)
7ed2c1a4 203
cd2c3dcd 204 await runCommand({ command, job: options.job })
5ba49f26 205
daf6e480 206 await fixHLSPlaylistIfNeeded(options)
837666fe
RK
207}
208
9252a33d
C
209// ---------------------------------------------------------------------------
210// Live muxing/transcoding functions
211// ---------------------------------------------------------------------------
123f6193 212
5a547f69
C
213async function getLiveTranscodingCommand (options: {
214 rtmpUrl: string
764b1a14 215
5a547f69 216 outPath: string
764b1a14
C
217 masterPlaylistName: string
218
5a547f69
C
219 resolutions: number[]
220 fps: number
5a547f69
C
221
222 availableEncoders: AvailableEncoders
223 profile: string
224}) {
764b1a14 225 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile, masterPlaylistName } = options
5a547f69
C
226 const input = rtmpUrl
227
55223d65 228 const command = getFFmpeg(input, 'live')
c6c0fa6c
C
229
230 const varStreamMap: string[] = []
231
b110820d 232 const complexFilter: ffmpeg.FilterSpecification[] = [
c6c0fa6c
C
233 {
234 inputs: '[v:0]',
235 filter: 'split',
236 options: resolutions.length,
237 outputs: resolutions.map(r => `vtemp${r}`)
3e03b961
C
238 }
239 ]
c6c0fa6c 240
49bcdb0d 241 command.outputOption('-sc_threshold 0')
c6c0fa6c 242
ce4a50b9
C
243 addDefaultEncoderGlobalParams({ command })
244
c6c0fa6c
C
245 for (let i = 0; i < resolutions.length; i++) {
246 const resolution = resolutions[i]
884d2c39
C
247 const resolutionFPS = computeFPS(fps, resolution)
248
249 const baseEncoderBuilderParams = {
250 input,
529b3752 251
884d2c39
C
252 availableEncoders,
253 profile,
529b3752 254
884d2c39
C
255 fps: resolutionFPS,
256 resolution,
257 streamNum: i,
258 videoType: 'live' as 'live'
259 }
5a547f69
C
260
261 {
529b3752
C
262 const streamType: StreamType = 'video'
263 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
5a547f69
C
264 if (!builderResult) {
265 throw new Error('No available live video encoder found')
266 }
267
268 command.outputOption(`-map [vout${resolution}]`)
269
884d2c39 270 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
5a547f69 271
1896bca0 272 logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
c6c0fa6c 273
5a547f69 274 command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
43f7a43c 275 applyEncoderOptions(command, builderResult.result)
3e03b961
C
276
277 complexFilter.push({
278 inputs: `vtemp${resolution}`,
279 filter: getScaleFilter(builderResult.result),
280 options: `w=-2:h=${resolution}`,
281 outputs: `vout${resolution}`
282 })
5a547f69
C
283 }
284
285 {
529b3752
C
286 const streamType: StreamType = 'audio'
287 const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
5a547f69
C
288 if (!builderResult) {
289 throw new Error('No available live audio encoder found')
290 }
c6c0fa6c 291
5a547f69
C
292 command.outputOption('-map a:0')
293
884d2c39 294 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
5a547f69 295
1896bca0 296 logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
5a547f69
C
297
298 command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
43f7a43c 299 applyEncoderOptions(command, builderResult.result)
5a547f69 300 }
c6c0fa6c
C
301
302 varStreamMap.push(`v:${i},a:${i}`)
303 }
304
3e03b961
C
305 command.complexFilter(complexFilter)
306
764b1a14 307 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
c6c0fa6c
C
308
309 command.outputOption('-var_stream_map', varStreamMap.join(' '))
310
c6c0fa6c
C
311 return command
312}
313
764b1a14 314function getLiveMuxingCommand (rtmpUrl: string, outPath: string, masterPlaylistName: string) {
55223d65 315 const command = getFFmpeg(rtmpUrl, 'live')
c6c0fa6c
C
316
317 command.outputOption('-c:v copy')
318 command.outputOption('-c:a copy')
319 command.outputOption('-map 0:a?')
320 command.outputOption('-map 0:v?')
321
764b1a14 322 addDefaultLiveHLSParams(command, outPath, masterPlaylistName)
c6c0fa6c 323
c6c0fa6c
C
324 return command
325}
326
5a547f69
C
327function buildStreamSuffix (base: string, streamNum?: number) {
328 if (streamNum !== undefined) {
329 return `${base}:${streamNum}`
330 }
331
332 return base
333}
334
9252a33d
C
335// ---------------------------------------------------------------------------
336// Default options
337// ---------------------------------------------------------------------------
338
ce4a50b9
C
339function addDefaultEncoderGlobalParams (options: {
340 command: ffmpeg.FfmpegCommand
341}) {
342 const { command } = options
343
344 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
345 command.outputOption('-max_muxing_queue_size 1024')
346 // strip all metadata
347 .outputOption('-map_metadata -1')
348 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
349 .outputOption('-b_strategy 1')
350 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
351 .outputOption('-bf 16')
352 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
353 .outputOption('-pix_fmt yuv420p')
354}
355
5a547f69
C
356function addDefaultEncoderParams (options: {
357 command: ffmpeg.FfmpegCommand
358 encoder: 'libx264' | string
359 streamNum?: number
360 fps?: number
361}) {
362 const { command, encoder, fps, streamNum } = options
363
364 if (encoder === 'libx264') {
365 // 3.1 is the minimal resource allocation for our highest supported resolution
ce4a50b9 366 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
5a547f69
C
367
368 if (fps) {
369 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
370 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
371 // https://superuser.com/a/908325
ce4a50b9 372 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
5a547f69
C
373 }
374 }
c6c0fa6c
C
375}
376
764b1a14 377function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string, masterPlaylistName: string) {
68e70a74 378 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
fb719404 379 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
49bcdb0d 380 command.outputOption('-hls_flags delete_segments+independent_segments')
21226063 381 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
764b1a14 382 command.outputOption('-master_pl_name ' + masterPlaylistName)
c6c0fa6c
C
383 command.outputOption(`-f hls`)
384
385 command.output(join(outPath, '%v.m3u8'))
386}
387
9252a33d
C
388// ---------------------------------------------------------------------------
389// Transcode VOD command builders
390// ---------------------------------------------------------------------------
391
392async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
14aed608 393 let fps = await getVideoFileFPS(options.inputPath)
884d2c39 394 fps = computeFPS(fps, options.resolution)
14aed608 395
3e03b961 396 let scaleFilterValue: string
14aed608
C
397
398 if (options.resolution !== undefined) {
3e03b961 399 scaleFilterValue = options.isPortraitMode === true
a60696ab
C
400 ? `w=${options.resolution}:h=-2`
401 : `w=-2:h=${options.resolution}`
14aed608
C
402 }
403
3e03b961
C
404 command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })
405
14aed608
C
406 return command
407}
408
536598cf
C
409async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
410 command = command.loop(undefined)
411
318b0bd0 412 const scaleFilterValue = getScaleCleanerValue()
3e03b961 413 command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
9252a33d 414
9252a33d 415 command.outputOption('-preset:v veryfast')
536598cf
C
416
417 command = command.input(options.audioPath)
536598cf
C
418 .outputOption('-tune stillimage')
419 .outputOption('-shortest')
420
421 return command
422}
423
daf6e480 424function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
a1587156 425 command = presetOnlyAudio(command)
5c7d6508 426
427 return command
428}
429
a1587156
C
430function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
431 command = presetCopy(command)
536598cf
C
432
433 command = command.outputOption('-map_metadata -1') // strip all metadata
434 .outputOption('-movflags faststart')
435
436 return command
437}
438
2650d6d4
C
439function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
440 return command.outputOption('-hls_time 4')
441 .outputOption('-hls_list_size 0')
442 .outputOption('-hls_playlist_type vod')
443 .outputOption('-hls_segment_filename ' + outputPath)
444 .outputOption('-hls_segment_type fmp4')
445 .outputOption('-f hls')
446 .outputOption('-hls_flags single_file')
447}
448
c6c0fa6c 449async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
14aed608
C
450 const videoPath = getHLSVideoPath(options)
451
a1587156 452 if (options.copyCodecs) command = presetCopy(command)
1c320673 453 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
9252a33d 454 else command = await buildx264VODCommand(command, options)
14aed608 455
2650d6d4
C
456 addCommonHLSVODCommandOptions(command, videoPath)
457
458 return command
459}
460
461async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
462 const videoPath = getHLSVideoPath(options)
463
3851e732 464 command.outputOption('-c copy')
e772bdf1
C
465
466 if (options.isAAC) {
467 // Required for example when copying an AAC stream from an MPEG-TS
468 // Since it's a bitstream filter, we don't need to reencode the audio
469 command.outputOption('-bsf:a aac_adtstoasc')
470 }
2650d6d4
C
471
472 addCommonHLSVODCommandOptions(command, videoPath)
14aed608
C
473
474 return command
475}
476
536598cf 477async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
2650d6d4 478 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
7f8f8bdb 479
7f8f8bdb
C
480 const fileContent = await readFile(options.outputPath)
481
482 const videoFileName = options.hlsPlaylist.videoFilename
483 const videoFilePath = getHLSVideoPath(options)
484
536598cf 485 // Fix wrong mapping with some ffmpeg versions
7f8f8bdb
C
486 const newContent = fileContent.toString()
487 .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)
488
489 await writeFile(options.outputPath, newContent)
490}
491
2650d6d4 492function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
9252a33d 493 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
4176e227
RK
494}
495
9252a33d
C
496// ---------------------------------------------------------------------------
497// Transcoding presets
498// ---------------------------------------------------------------------------
499
529b3752
C
500// Run encoder builder depending on available encoders
501// Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
502// If the default one does not exist, check the next encoder
5a547f69 503async function getEncoderBuilderResult (options: {
529b3752 504 streamType: 'video' | 'audio'
5a547f69
C
505 input: string
506
507 availableEncoders: AvailableEncoders
508 profile: string
509
510 videoType: 'vod' | 'live'
511
512 resolution: number
513 fps?: number
514 streamNum?: number
515}) {
516 const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options
517
1896bca0
C
518 const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
519 const encoders = availableEncoders.available[videoType]
5a547f69
C
520
521 for (const encoder of encodersToTry) {
1896bca0
C
522 if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
523 logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
524 continue
525 }
526
527 if (!encoders[encoder]) {
528 logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
529 continue
530 }
5a547f69 531
529b3752
C
532 // An object containing available profiles for this encoder
533 const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
5a547f69
C
534 let builder = builderProfiles[profile]
535
536 if (!builder) {
537 logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
538 builder = builderProfiles.default
529b3752
C
539
540 if (!builder) {
541 logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
542 continue
543 }
5a547f69
C
544 }
545
318b0bd0 546 const result = await builder({ input, resolution, fps, streamNum })
5a547f69
C
547
548 return {
549 result,
550
551 // If we don't have output options, then copy the input stream
552 encoder: result.copy === true
553 ? 'copy'
554 : encoder
555 }
556 }
557
558 return null
559}
560
3e03b961
C
561async function presetVideo (options: {
562 command: ffmpeg.FfmpegCommand
563 input: string
564 transcodeOptions: TranscodeOptions
9252a33d 565 fps?: number
3e03b961
C
566 scaleFilterValue?: string
567}) {
568 const { command, input, transcodeOptions, fps, scaleFilterValue } = options
569
cdf4cb9e 570 let localCommand = command
4176e227 571 .format('mp4')
4176e227 572 .outputOption('-movflags faststart')
4176e227 573
ce4a50b9
C
574 addDefaultEncoderGlobalParams({ command })
575
9252a33d 576 // Audio encoder
daf6e480 577 const parsedAudio = await getAudioStream(input)
4176e227 578
529b3752 579 let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
9252a33d 580
cdf4cb9e
C
581 if (!parsedAudio.audioStream) {
582 localCommand = localCommand.noAudio()
1896bca0 583 streamsToProcess = [ 'video' ]
9252a33d 584 }
536598cf 585
5a547f69
C
586 for (const streamType of streamsToProcess) {
587 const { profile, resolution, availableEncoders } = transcodeOptions
588
589 const builderResult = await getEncoderBuilderResult({
590 streamType,
591 input,
592 resolution,
593 availableEncoders,
594 profile,
595 fps,
596 videoType: 'vod' as 'vod'
597 })
9252a33d 598
5a547f69
C
599 if (!builderResult) {
600 throw new Error('No available encoder found for stream ' + streamType)
601 }
9252a33d 602
1896bca0
C
603 logger.debug(
604 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
605 builderResult.encoder, streamType, input, profile, builderResult
606 )
9252a33d 607
529b3752 608 if (streamType === 'video') {
5a547f69 609 localCommand.videoCodec(builderResult.encoder)
3e03b961
C
610
611 if (scaleFilterValue) {
612 localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
613 }
529b3752 614 } else if (streamType === 'audio') {
5a547f69 615 localCommand.audioCodec(builderResult.encoder)
9252a33d 616 }
3e03b961 617
43f7a43c 618 applyEncoderOptions(localCommand, builderResult.result)
5a547f69 619 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
536598cf 620 }
bcf21a37 621
cdf4cb9e 622 return localCommand
4176e227 623}
14aed608 624
a1587156 625function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
14aed608
C
626 return command
627 .format('mp4')
628 .videoCodec('copy')
629 .audioCodec('copy')
630}
5c7d6508 631
a1587156 632function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
5c7d6508 633 return command
634 .format('mp4')
635 .audioCodec('copy')
636 .noVideo()
637}
c6c0fa6c 638
43f7a43c
TLC
639function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
640 return command
641 .inputOptions(options.inputOptions ?? [])
43f7a43c
TLC
642 .outputOptions(options.outputOptions ?? [])
643}
644
3e03b961
C
645function getScaleFilter (options: EncoderOptions): string {
646 if (options.scaleFilter) return options.scaleFilter.name
647
648 return 'scale'
649}
650
9252a33d
C
651// ---------------------------------------------------------------------------
652// Utils
653// ---------------------------------------------------------------------------
654
55223d65 655function getFFmpeg (input: string, type: 'live' | 'vod') {
c6c0fa6c 656 // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
7abb6060
RK
657 const command = ffmpeg(input, {
658 niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
659 cwd: CONFIG.STORAGE.TMP_DIR
660 })
c6c0fa6c 661
55223d65
C
662 const threads = type === 'live'
663 ? CONFIG.LIVE.TRANSCODING.THREADS
664 : CONFIG.TRANSCODING.THREADS
665
666 if (threads > 0) {
c6c0fa6c 667 // If we don't set any threads ffmpeg will chose automatically
55223d65 668 command.outputOption('-threads ' + threads)
c6c0fa6c
C
669 }
670
671 return command
672}
9252a33d 673
ae71acca
C
674function getFFmpegVersion () {
675 return new Promise<string>((res, rej) => {
676 (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
677 if (err) return rej(err)
678 if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))
679
680 return execPromise(`${ffmpegPath} -version`)
681 .then(stdout => {
60f1f615 682 const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
ae71acca
C
683 if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))
684
60f1f615
C
685 // Fix ffmpeg version that does not include patch version (4.4 for example)
686 let version = parsed[1]
1ff9f1cd 687 if (version.match(/^\d+\.\d+$/)) {
60f1f615
C
688 version += '.0'
689 }
690
691 return res(version)
ae71acca
C
692 })
693 .catch(err => rej(err))
694 })
695 })
696}
697
cd2c3dcd
C
698async function runCommand (options: {
699 command: ffmpeg.FfmpegCommand
700 silent?: boolean // false
701 job?: Job
702}) {
703 const { command, silent = false, job } = options
704
9252a33d
C
705 return new Promise<void>((res, rej) => {
706 command.on('error', (err, stdout, stderr) => {
cd2c3dcd
C
707 if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })
708
9252a33d
C
709 rej(err)
710 })
711
dd9c7929
C
712 command.on('end', (stdout, stderr) => {
713 logger.debug('FFmpeg command ended.', { stdout, stderr })
714
9252a33d
C
715 res()
716 })
717
3b01f4c0
C
718 if (job) {
719 command.on('progress', progress => {
720 if (!progress.percent) return
721
722 job.progress(Math.round(progress.percent))
723 .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
724 })
725 }
726
9252a33d
C
727 command.run()
728 })
729}
09849603 730
318b0bd0
C
731// Avoid "height not divisible by 2" error
732function getScaleCleanerValue () {
733 return 'trunc(iw/2)*2:trunc(ih/2)*2'
734}
735
09849603
RK
736// ---------------------------------------------------------------------------
737
738export {
739 getLiveTranscodingCommand,
740 getLiveMuxingCommand,
741 buildStreamSuffix,
742 convertWebPToJPG,
743 processGIF,
744 generateImageFromVideoFile,
745 TranscodeOptions,
746 TranscodeOptionsType,
747 transcode,
748 runCommand,
ae71acca 749 getFFmpegVersion,
09849603 750
1896bca0
C
751 resetSupportedEncoders,
752
09849603
RK
753 // builders
754 buildx264VODCommand
755}