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