]>
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 | ||
140 | hlsPlaylist: { | |
141 | videoFilename: string | |
142 | } | |
143 | } | |
144 | ||
536598cf C |
145 | interface QuickTranscodeOptions extends BaseTranscodeOptions { |
146 | type: 'quick-transcode' | |
147 | } | |
148 | ||
149 | interface VideoTranscodeOptions extends BaseTranscodeOptions { | |
150 | type: 'video' | |
151 | } | |
152 | ||
153 | interface MergeAudioTranscodeOptions extends BaseTranscodeOptions { | |
154 | type: 'merge-audio' | |
155 | audioPath: string | |
156 | } | |
157 | ||
3a149e9f C |
158 | interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions { |
159 | type: 'only-audio' | |
5c7d6508 | 160 | } |
161 | ||
a1587156 C |
162 | type TranscodeOptions = |
163 | HLSTranscodeOptions | |
2650d6d4 | 164 | | HLSFromTSTranscodeOptions |
3a149e9f C |
165 | | VideoTranscodeOptions |
166 | | MergeAudioTranscodeOptions | |
167 | | OnlyAudioTranscodeOptions | |
168 | | QuickTranscodeOptions | |
536598cf | 169 | |
daf6e480 C |
170 | const builders: { |
171 | [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand | |
172 | } = { | |
173 | 'quick-transcode': buildQuickTranscodeCommand, | |
174 | 'hls': buildHLSVODCommand, | |
2650d6d4 | 175 | 'hls-from-ts': buildHLSVODFromTSCommand, |
daf6e480 C |
176 | 'merge-audio': buildAudioMergeCommand, |
177 | 'only-audio': buildOnlyAudioCommand, | |
9252a33d | 178 | 'video': buildx264VODCommand |
daf6e480 C |
179 | } |
180 | ||
181 | async function transcode (options: TranscodeOptions) { | |
9e2b2e76 C |
182 | logger.debug('Will run transcode.', { options }) |
183 | ||
55223d65 | 184 | let command = getFFmpeg(options.inputPath, 'vod') |
daf6e480 | 185 | .output(options.outputPath) |
14d3270f | 186 | |
daf6e480 | 187 | command = await builders[options.type](command, options) |
7ed2c1a4 | 188 | |
daf6e480 | 189 | await runCommand(command) |
5ba49f26 | 190 | |
daf6e480 | 191 | await fixHLSPlaylistIfNeeded(options) |
837666fe RK |
192 | } |
193 | ||
9252a33d C |
194 | // --------------------------------------------------------------------------- |
195 | // Live muxing/transcoding functions | |
196 | // --------------------------------------------------------------------------- | |
123f6193 | 197 | |
5a547f69 C |
198 | async function getLiveTranscodingCommand (options: { |
199 | rtmpUrl: string | |
200 | outPath: string | |
201 | resolutions: number[] | |
202 | fps: number | |
5a547f69 C |
203 | |
204 | availableEncoders: AvailableEncoders | |
205 | profile: string | |
206 | }) { | |
937581b8 | 207 | const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options |
5a547f69 C |
208 | const input = rtmpUrl |
209 | ||
55223d65 | 210 | const command = getFFmpeg(input, 'live') |
c6c0fa6c C |
211 | |
212 | const varStreamMap: string[] = [] | |
213 | ||
214 | command.complexFilter([ | |
215 | { | |
216 | inputs: '[v:0]', | |
217 | filter: 'split', | |
218 | options: resolutions.length, | |
219 | outputs: resolutions.map(r => `vtemp${r}`) | |
220 | }, | |
221 | ||
222 | ...resolutions.map(r => ({ | |
223 | inputs: `vtemp${r}`, | |
224 | filter: 'scale', | |
225 | options: `w=-2:h=${r}`, | |
226 | outputs: `vout${r}` | |
227 | })) | |
228 | ]) | |
229 | ||
c6c0fa6c | 230 | command.outputOption('-preset superfast') |
49bcdb0d | 231 | command.outputOption('-sc_threshold 0') |
c6c0fa6c | 232 | |
ce4a50b9 C |
233 | addDefaultEncoderGlobalParams({ command }) |
234 | ||
c6c0fa6c C |
235 | for (let i = 0; i < resolutions.length; i++) { |
236 | const resolution = resolutions[i] | |
884d2c39 C |
237 | const resolutionFPS = computeFPS(fps, resolution) |
238 | ||
239 | const baseEncoderBuilderParams = { | |
240 | input, | |
241 | availableEncoders, | |
242 | profile, | |
243 | fps: resolutionFPS, | |
244 | resolution, | |
245 | streamNum: i, | |
246 | videoType: 'live' as 'live' | |
247 | } | |
5a547f69 C |
248 | |
249 | { | |
250 | const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'VIDEO' })) | |
251 | if (!builderResult) { | |
252 | throw new Error('No available live video encoder found') | |
253 | } | |
254 | ||
255 | command.outputOption(`-map [vout${resolution}]`) | |
256 | ||
884d2c39 | 257 | addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i }) |
5a547f69 C |
258 | |
259 | logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult) | |
c6c0fa6c | 260 | |
5a547f69 C |
261 | command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`) |
262 | command.addOutputOptions(builderResult.result.outputOptions) | |
263 | } | |
264 | ||
265 | { | |
266 | const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType: 'AUDIO' })) | |
267 | if (!builderResult) { | |
268 | throw new Error('No available live audio encoder found') | |
269 | } | |
c6c0fa6c | 270 | |
5a547f69 C |
271 | command.outputOption('-map a:0') |
272 | ||
884d2c39 | 273 | addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i }) |
5a547f69 C |
274 | |
275 | logger.debug('Apply ffmpeg live audio params from %s.', builderResult.encoder, builderResult) | |
276 | ||
277 | command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`) | |
278 | command.addOutputOptions(builderResult.result.outputOptions) | |
279 | } | |
c6c0fa6c C |
280 | |
281 | varStreamMap.push(`v:${i},a:${i}`) | |
282 | } | |
283 | ||
937581b8 | 284 | addDefaultLiveHLSParams(command, outPath) |
c6c0fa6c C |
285 | |
286 | command.outputOption('-var_stream_map', varStreamMap.join(' ')) | |
287 | ||
c6c0fa6c C |
288 | return command |
289 | } | |
290 | ||
937581b8 | 291 | function getLiveMuxingCommand (rtmpUrl: string, outPath: string) { |
55223d65 | 292 | const command = getFFmpeg(rtmpUrl, 'live') |
c6c0fa6c C |
293 | |
294 | command.outputOption('-c:v copy') | |
295 | command.outputOption('-c:a copy') | |
296 | command.outputOption('-map 0:a?') | |
297 | command.outputOption('-map 0:v?') | |
298 | ||
937581b8 | 299 | addDefaultLiveHLSParams(command, outPath) |
c6c0fa6c | 300 | |
c6c0fa6c C |
301 | return command |
302 | } | |
303 | ||
5a547f69 C |
304 | function buildStreamSuffix (base: string, streamNum?: number) { |
305 | if (streamNum !== undefined) { | |
306 | return `${base}:${streamNum}` | |
307 | } | |
308 | ||
309 | return base | |
310 | } | |
311 | ||
14d3270f C |
312 | // --------------------------------------------------------------------------- |
313 | ||
314 | export { | |
9252a33d C |
315 | getLiveTranscodingCommand, |
316 | getLiveMuxingCommand, | |
5a547f69 | 317 | buildStreamSuffix, |
18782242 | 318 | convertWebPToJPG, |
123f6193 | 319 | processGIF, |
14d3270f | 320 | generateImageFromVideoFile, |
536598cf C |
321 | TranscodeOptions, |
322 | TranscodeOptionsType, | |
2650d6d4 | 323 | transcode |
73c69591 C |
324 | } |
325 | ||
326 | // --------------------------------------------------------------------------- | |
327 | ||
9252a33d C |
328 | // --------------------------------------------------------------------------- |
329 | // Default options | |
330 | // --------------------------------------------------------------------------- | |
331 | ||
ce4a50b9 C |
332 | function addDefaultEncoderGlobalParams (options: { |
333 | command: ffmpeg.FfmpegCommand | |
334 | }) { | |
335 | const { command } = options | |
336 | ||
337 | // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375 | |
338 | command.outputOption('-max_muxing_queue_size 1024') | |
339 | // strip all metadata | |
340 | .outputOption('-map_metadata -1') | |
341 | // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it | |
342 | .outputOption('-b_strategy 1') | |
343 | // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16 | |
344 | .outputOption('-bf 16') | |
345 | // allows import of source material with incompatible pixel formats (e.g. MJPEG video) | |
346 | .outputOption('-pix_fmt yuv420p') | |
347 | } | |
348 | ||
5a547f69 C |
349 | function addDefaultEncoderParams (options: { |
350 | command: ffmpeg.FfmpegCommand | |
351 | encoder: 'libx264' | string | |
352 | streamNum?: number | |
353 | fps?: number | |
354 | }) { | |
355 | const { command, encoder, fps, streamNum } = options | |
356 | ||
357 | if (encoder === 'libx264') { | |
358 | // 3.1 is the minimal resource allocation for our highest supported resolution | |
ce4a50b9 | 359 | command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1') |
5a547f69 C |
360 | |
361 | if (fps) { | |
362 | // Keyframe interval of 2 seconds for faster seeking and resolution switching. | |
363 | // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html | |
364 | // https://superuser.com/a/908325 | |
ce4a50b9 | 365 | command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2)) |
5a547f69 C |
366 | } |
367 | } | |
c6c0fa6c C |
368 | } |
369 | ||
937581b8 | 370 | function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) { |
68e70a74 | 371 | command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS) |
fb719404 | 372 | command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE) |
49bcdb0d | 373 | command.outputOption('-hls_flags delete_segments+independent_segments') |
21226063 | 374 | command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`) |
c6c0fa6c C |
375 | command.outputOption('-master_pl_name master.m3u8') |
376 | command.outputOption(`-f hls`) | |
377 | ||
378 | command.output(join(outPath, '%v.m3u8')) | |
379 | } | |
380 | ||
9252a33d C |
381 | // --------------------------------------------------------------------------- |
382 | // Transcode VOD command builders | |
383 | // --------------------------------------------------------------------------- | |
384 | ||
385 | async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) { | |
14aed608 | 386 | let fps = await getVideoFileFPS(options.inputPath) |
884d2c39 | 387 | fps = computeFPS(fps, options.resolution) |
14aed608 | 388 | |
9252a33d | 389 | command = await presetVideo(command, options.inputPath, options, fps) |
14aed608 C |
390 | |
391 | if (options.resolution !== undefined) { | |
392 | // '?x720' or '720x?' for example | |
5a547f69 C |
393 | const size = options.isPortraitMode === true |
394 | ? `${options.resolution}x?` | |
395 | : `?x${options.resolution}` | |
396 | ||
14aed608 C |
397 | command = command.size(size) |
398 | } | |
399 | ||
14aed608 C |
400 | return command |
401 | } | |
402 | ||
536598cf C |
403 | async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) { |
404 | command = command.loop(undefined) | |
405 | ||
9252a33d C |
406 | command = await presetVideo(command, options.audioPath, options) |
407 | ||
9252a33d | 408 | command.outputOption('-preset:v veryfast') |
536598cf C |
409 | |
410 | command = command.input(options.audioPath) | |
411 | .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error | |
412 | .outputOption('-tune stillimage') | |
413 | .outputOption('-shortest') | |
414 | ||
415 | return command | |
416 | } | |
417 | ||
daf6e480 | 418 | function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) { |
a1587156 | 419 | command = presetOnlyAudio(command) |
5c7d6508 | 420 | |
421 | return command | |
422 | } | |
423 | ||
a1587156 C |
424 | function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) { |
425 | command = presetCopy(command) | |
536598cf C |
426 | |
427 | command = command.outputOption('-map_metadata -1') // strip all metadata | |
428 | .outputOption('-movflags faststart') | |
429 | ||
430 | return command | |
431 | } | |
432 | ||
2650d6d4 C |
433 | function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) { |
434 | return command.outputOption('-hls_time 4') | |
435 | .outputOption('-hls_list_size 0') | |
436 | .outputOption('-hls_playlist_type vod') | |
437 | .outputOption('-hls_segment_filename ' + outputPath) | |
438 | .outputOption('-hls_segment_type fmp4') | |
439 | .outputOption('-f hls') | |
440 | .outputOption('-hls_flags single_file') | |
441 | } | |
442 | ||
c6c0fa6c | 443 | async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) { |
14aed608 C |
444 | const videoPath = getHLSVideoPath(options) |
445 | ||
a1587156 | 446 | if (options.copyCodecs) command = presetCopy(command) |
1c320673 | 447 | else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command) |
9252a33d | 448 | else command = await buildx264VODCommand(command, options) |
14aed608 | 449 | |
2650d6d4 C |
450 | addCommonHLSVODCommandOptions(command, videoPath) |
451 | ||
452 | return command | |
453 | } | |
454 | ||
455 | async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) { | |
456 | const videoPath = getHLSVideoPath(options) | |
457 | ||
458 | command.inputOption('-safe 0') | |
459 | command.inputOption('-f concat') | |
460 | ||
461 | command.outputOption('-c:v copy') | |
462 | command.audioFilter('aresample=async=1:first_pts=0') | |
463 | ||
464 | addCommonHLSVODCommandOptions(command, videoPath) | |
14aed608 C |
465 | |
466 | return command | |
467 | } | |
468 | ||
536598cf | 469 | async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) { |
2650d6d4 | 470 | if (options.type !== 'hls' && options.type !== 'hls-from-ts') return |
7f8f8bdb | 471 | |
7f8f8bdb C |
472 | const fileContent = await readFile(options.outputPath) |
473 | ||
474 | const videoFileName = options.hlsPlaylist.videoFilename | |
475 | const videoFilePath = getHLSVideoPath(options) | |
476 | ||
536598cf | 477 | // Fix wrong mapping with some ffmpeg versions |
7f8f8bdb C |
478 | const newContent = fileContent.toString() |
479 | .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`) | |
480 | ||
481 | await writeFile(options.outputPath, newContent) | |
482 | } | |
483 | ||
2650d6d4 | 484 | function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) { |
9252a33d | 485 | return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}` |
4176e227 RK |
486 | } |
487 | ||
9252a33d C |
488 | // --------------------------------------------------------------------------- |
489 | // Transcoding presets | |
490 | // --------------------------------------------------------------------------- | |
491 | ||
5a547f69 C |
492 | async function getEncoderBuilderResult (options: { |
493 | streamType: string | |
494 | input: string | |
495 | ||
496 | availableEncoders: AvailableEncoders | |
497 | profile: string | |
498 | ||
499 | videoType: 'vod' | 'live' | |
500 | ||
501 | resolution: number | |
502 | fps?: number | |
503 | streamNum?: number | |
504 | }) { | |
505 | const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options | |
506 | ||
507 | const encodersToTry: string[] = VIDEO_TRANSCODING_ENCODERS[streamType] | |
508 | ||
509 | for (const encoder of encodersToTry) { | |
510 | if (!(await checkFFmpegEncoders()).get(encoder) || !availableEncoders[videoType][encoder]) continue | |
511 | ||
512 | const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = availableEncoders[videoType][encoder] | |
513 | let builder = builderProfiles[profile] | |
514 | ||
515 | if (!builder) { | |
516 | logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder) | |
517 | builder = builderProfiles.default | |
518 | } | |
519 | ||
520 | const result = await builder({ input, resolution: resolution, fps, streamNum }) | |
521 | ||
522 | return { | |
523 | result, | |
524 | ||
525 | // If we don't have output options, then copy the input stream | |
526 | encoder: result.copy === true | |
527 | ? 'copy' | |
528 | : encoder | |
529 | } | |
530 | } | |
531 | ||
532 | return null | |
533 | } | |
534 | ||
9252a33d C |
535 | async function presetVideo ( |
536 | command: ffmpeg.FfmpegCommand, | |
537 | input: string, | |
538 | transcodeOptions: TranscodeOptions, | |
539 | fps?: number | |
540 | ) { | |
cdf4cb9e | 541 | let localCommand = command |
4176e227 | 542 | .format('mp4') |
4176e227 | 543 | .outputOption('-movflags faststart') |
4176e227 | 544 | |
ce4a50b9 C |
545 | addDefaultEncoderGlobalParams({ command }) |
546 | ||
9252a33d | 547 | // Audio encoder |
daf6e480 | 548 | const parsedAudio = await getAudioStream(input) |
4176e227 | 549 | |
9252a33d | 550 | let streamsToProcess = [ 'AUDIO', 'VIDEO' ] |
9252a33d | 551 | |
cdf4cb9e C |
552 | if (!parsedAudio.audioStream) { |
553 | localCommand = localCommand.noAudio() | |
9252a33d C |
554 | streamsToProcess = [ 'VIDEO' ] |
555 | } | |
536598cf | 556 | |
5a547f69 C |
557 | for (const streamType of streamsToProcess) { |
558 | const { profile, resolution, availableEncoders } = transcodeOptions | |
559 | ||
560 | const builderResult = await getEncoderBuilderResult({ | |
561 | streamType, | |
562 | input, | |
563 | resolution, | |
564 | availableEncoders, | |
565 | profile, | |
566 | fps, | |
567 | videoType: 'vod' as 'vod' | |
568 | }) | |
9252a33d | 569 | |
5a547f69 C |
570 | if (!builderResult) { |
571 | throw new Error('No available encoder found for stream ' + streamType) | |
572 | } | |
9252a33d | 573 | |
5a547f69 | 574 | logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult) |
9252a33d | 575 | |
5a547f69 C |
576 | if (streamType === 'VIDEO') { |
577 | localCommand.videoCodec(builderResult.encoder) | |
578 | } else if (streamType === 'AUDIO') { | |
579 | localCommand.audioCodec(builderResult.encoder) | |
9252a33d C |
580 | } |
581 | ||
5a547f69 C |
582 | command.addOutputOptions(builderResult.result.outputOptions) |
583 | addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps }) | |
536598cf | 584 | } |
bcf21a37 | 585 | |
cdf4cb9e | 586 | return localCommand |
4176e227 | 587 | } |
14aed608 | 588 | |
a1587156 | 589 | function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand { |
14aed608 C |
590 | return command |
591 | .format('mp4') | |
592 | .videoCodec('copy') | |
593 | .audioCodec('copy') | |
594 | } | |
5c7d6508 | 595 | |
a1587156 | 596 | function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand { |
5c7d6508 | 597 | return command |
598 | .format('mp4') | |
599 | .audioCodec('copy') | |
600 | .noVideo() | |
601 | } | |
c6c0fa6c | 602 | |
9252a33d C |
603 | // --------------------------------------------------------------------------- |
604 | // Utils | |
605 | // --------------------------------------------------------------------------- | |
606 | ||
55223d65 | 607 | function getFFmpeg (input: string, type: 'live' | 'vod') { |
c6c0fa6c C |
608 | // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems |
609 | const command = ffmpeg(input, { niceness: FFMPEG_NICE.TRANSCODING, cwd: CONFIG.STORAGE.TMP_DIR }) | |
610 | ||
55223d65 C |
611 | const threads = type === 'live' |
612 | ? CONFIG.LIVE.TRANSCODING.THREADS | |
613 | : CONFIG.TRANSCODING.THREADS | |
614 | ||
615 | if (threads > 0) { | |
c6c0fa6c | 616 | // If we don't set any threads ffmpeg will chose automatically |
55223d65 | 617 | command.outputOption('-threads ' + threads) |
c6c0fa6c C |
618 | } |
619 | ||
620 | return command | |
621 | } | |
9252a33d C |
622 | |
623 | async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) { | |
624 | return new Promise<void>((res, rej) => { | |
625 | command.on('error', (err, stdout, stderr) => { | |
626 | if (onEnd) onEnd() | |
627 | ||
628 | logger.error('Error in transcoding job.', { stdout, stderr }) | |
629 | rej(err) | |
630 | }) | |
631 | ||
632 | command.on('end', () => { | |
633 | if (onEnd) onEnd() | |
634 | ||
635 | res() | |
636 | }) | |
637 | ||
638 | command.run() | |
639 | }) | |
640 | } |