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