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