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