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