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