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