]>
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' |
ae71acca | 8 | import { execPromise, 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' |
14d3270f | 13 | |
6b67897e C |
14 | /** |
15 | * | |
16 | * Functions that run transcoding/muxing ffmpeg processes | |
17 | * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts | |
18 | * | |
19 | */ | |
20 | ||
9252a33d C |
21 | // --------------------------------------------------------------------------- |
22 | // Encoder options | |
23 | // --------------------------------------------------------------------------- | |
24 | ||
1896bca0 | 25 | type StreamType = 'audio' | 'video' |
9252a33d | 26 | |
1896bca0 C |
27 | // --------------------------------------------------------------------------- |
28 | // Encoders support | |
29 | // --------------------------------------------------------------------------- | |
9252a33d | 30 | |
1896bca0 C |
31 | // Detect supported encoders by ffmpeg |
32 | let supportedEncoders: Map<string, boolean> | |
33 | async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> { | |
34 | if (supportedEncoders !== undefined) { | |
35 | return supportedEncoders | |
36 | } | |
9252a33d | 37 | |
1896bca0 C |
38 | const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders) |
39 | const availableFFmpegEncoders = await getAvailableEncodersPromise() | |
9252a33d | 40 | |
1896bca0 C |
41 | const searchEncoders = new Set<string>() |
42 | for (const type of [ 'live', 'vod' ]) { | |
43 | for (const streamType of [ 'audio', 'video' ]) { | |
44 | for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) { | |
45 | searchEncoders.add(encoder) | |
46 | } | |
47 | } | |
48 | } | |
9252a33d | 49 | |
1896bca0 | 50 | supportedEncoders = new Map<string, boolean>() |
9252a33d | 51 | |
1896bca0 C |
52 | for (const searchEncoder of searchEncoders) { |
53 | supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined) | |
529b3752 C |
54 | } |
55 | ||
1896bca0 | 56 | logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders }) |
529b3752 | 57 | |
1896bca0 | 58 | return supportedEncoders |
9252a33d C |
59 | } |
60 | ||
1896bca0 C |
61 | function resetSupportedEncoders () { |
62 | supportedEncoders = undefined | |
63 | } | |
529b3752 | 64 | |
9252a33d C |
65 | // --------------------------------------------------------------------------- |
66 | // Image manipulation | |
67 | // --------------------------------------------------------------------------- | |
68 | ||
69 | function convertWebPToJPG (path: string, destination: string): Promise<void> { | |
a4a8cd39 | 70 | const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL }) |
9252a33d C |
71 | .output(destination) |
72 | ||
cd2c3dcd | 73 | return runCommand({ command, silent: true }) |
9252a33d C |
74 | } |
75 | ||
76 | function processGIF ( | |
77 | path: string, | |
78 | destination: string, | |
f619de0e | 79 | newSize: { width: number, height: number } |
9252a33d | 80 | ): Promise<void> { |
a4a8cd39 | 81 | const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL }) |
f619de0e C |
82 | .fps(20) |
83 | .size(`${newSize.width}x${newSize.height}`) | |
84 | .output(destination) | |
9252a33d | 85 | |
cd2c3dcd | 86 | return runCommand({ command }) |
9252a33d C |
87 | } |
88 | ||
26670720 C |
89 | async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) { |
90 | const pendingImageName = 'pending-' + imageName | |
91 | ||
14d3270f | 92 | const options = { |
26670720 | 93 | filename: pendingImageName, |
14d3270f C |
94 | count: 1, |
95 | folder | |
96 | } | |
97 | ||
26670720 | 98 | const pendingImagePath = join(folder, pendingImageName) |
6fdc553a C |
99 | |
100 | try { | |
101 | await new Promise<string>((res, rej) => { | |
7160878c | 102 | ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL }) |
6fdc553a C |
103 | .on('error', rej) |
104 | .on('end', () => res(imageName)) | |
105 | .thumbnail(options) | |
106 | }) | |
107 | ||
108 | const destination = join(folder, imageName) | |
2fb5b3a5 | 109 | await processImage(pendingImagePath, destination, size) |
6fdc553a | 110 | } catch (err) { |
d5b7d911 | 111 | logger.error('Cannot generate image from video %s.', fromPath, { err }) |
6fdc553a C |
112 | |
113 | try { | |
62689b94 | 114 | await remove(pendingImagePath) |
6fdc553a | 115 | } catch (err) { |
d5b7d911 | 116 | logger.debug('Cannot remove pending image path after generation error.', { err }) |
6fdc553a C |
117 | } |
118 | } | |
14d3270f C |
119 | } |
120 | ||
daf6e480 C |
121 | // --------------------------------------------------------------------------- |
122 | // Transcode meta function | |
123 | // --------------------------------------------------------------------------- | |
124 | ||
2650d6d4 | 125 | type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio' |
536598cf C |
126 | |
127 | interface BaseTranscodeOptions { | |
128 | type: TranscodeOptionsType | |
9252a33d | 129 | |
14d3270f C |
130 | inputPath: string |
131 | outputPath: string | |
9252a33d C |
132 | |
133 | availableEncoders: AvailableEncoders | |
134 | profile: string | |
135 | ||
09209296 | 136 | resolution: VideoResolution |
9252a33d | 137 | |
056aa7f2 | 138 | isPortraitMode?: boolean |
3b01f4c0 C |
139 | |
140 | job?: Job | |
536598cf | 141 | } |
09209296 | 142 | |
536598cf C |
143 | interface HLSTranscodeOptions extends BaseTranscodeOptions { |
144 | type: 'hls' | |
d7a25329 | 145 | copyCodecs: boolean |
536598cf | 146 | hlsPlaylist: { |
4c280004 C |
147 | videoFilename: string |
148 | } | |
14d3270f C |
149 | } |
150 | ||
2650d6d4 C |
151 | interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions { |
152 | type: 'hls-from-ts' | |
153 | ||
e772bdf1 C |
154 | isAAC: boolean |
155 | ||
2650d6d4 C |
156 | hlsPlaylist: { |
157 | videoFilename: string | |
158 | } | |
159 | } | |
160 | ||
536598cf C |
161 | interface QuickTranscodeOptions extends BaseTranscodeOptions { |
162 | type: 'quick-transcode' | |
163 | } | |
164 | ||
165 | interface VideoTranscodeOptions extends BaseTranscodeOptions { | |
166 | type: 'video' | |
167 | } | |
168 | ||
169 | interface MergeAudioTranscodeOptions extends BaseTranscodeOptions { | |
170 | type: 'merge-audio' | |
171 | audioPath: string | |
172 | } | |
173 | ||
3a149e9f C |
174 | interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions { |
175 | type: 'only-audio' | |
5c7d6508 | 176 | } |
177 | ||
a1587156 C |
178 | type TranscodeOptions = |
179 | HLSTranscodeOptions | |
2650d6d4 | 180 | | HLSFromTSTranscodeOptions |
3a149e9f C |
181 | | VideoTranscodeOptions |
182 | | MergeAudioTranscodeOptions | |
183 | | OnlyAudioTranscodeOptions | |
184 | | QuickTranscodeOptions | |
536598cf | 185 | |
daf6e480 C |
186 | const builders: { |
187 | [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand | |
188 | } = { | |
189 | 'quick-transcode': buildQuickTranscodeCommand, | |
190 | 'hls': buildHLSVODCommand, | |
2650d6d4 | 191 | 'hls-from-ts': buildHLSVODFromTSCommand, |
daf6e480 C |
192 | 'merge-audio': buildAudioMergeCommand, |
193 | 'only-audio': buildOnlyAudioCommand, | |
9252a33d | 194 | 'video': buildx264VODCommand |
daf6e480 C |
195 | } |
196 | ||
197 | async function transcode (options: TranscodeOptions) { | |
9e2b2e76 C |
198 | logger.debug('Will run transcode.', { options }) |
199 | ||
55223d65 | 200 | let command = getFFmpeg(options.inputPath, 'vod') |
daf6e480 | 201 | .output(options.outputPath) |
14d3270f | 202 | |
daf6e480 | 203 | command = await builders[options.type](command, options) |
7ed2c1a4 | 204 | |
cd2c3dcd | 205 | await runCommand({ command, job: options.job }) |
5ba49f26 | 206 | |
daf6e480 | 207 | await fixHLSPlaylistIfNeeded(options) |
837666fe RK |
208 | } |
209 | ||
9252a33d C |
210 | // --------------------------------------------------------------------------- |
211 | // Live muxing/transcoding functions | |
212 | // --------------------------------------------------------------------------- | |
123f6193 | 213 | |
5a547f69 C |
214 | async function getLiveTranscodingCommand (options: { |
215 | rtmpUrl: string | |
216 | outPath: string | |
217 | resolutions: number[] | |
218 | fps: number | |
5a547f69 C |
219 | |
220 | availableEncoders: AvailableEncoders | |
221 | profile: string | |
222 | }) { | |
937581b8 | 223 | const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options |
5a547f69 C |
224 | const input = rtmpUrl |
225 | ||
55223d65 | 226 | const command = getFFmpeg(input, 'live') |
c6c0fa6c C |
227 | |
228 | const varStreamMap: string[] = [] | |
229 | ||
3e03b961 | 230 | const complexFilter: FilterSpecification[] = [ |
c6c0fa6c C |
231 | { |
232 | inputs: '[v:0]', | |
233 | filter: 'split', | |
234 | options: resolutions.length, | |
235 | outputs: resolutions.map(r => `vtemp${r}`) | |
3e03b961 C |
236 | } |
237 | ] | |
c6c0fa6c | 238 | |
c6c0fa6c | 239 | command.outputOption('-preset superfast') |
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 | ||
3e03b961 C |
411 | // Avoid "height not divisible by 2" error |
412 | const scaleFilterValue = 'trunc(iw/2)*2:trunc(ih/2)*2' | |
413 | command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue }) | |
9252a33d | 414 | |
9252a33d | 415 | command.outputOption('-preset:v veryfast') |
536598cf C |
416 | |
417 | command = command.input(options.audioPath) | |
536598cf C |
418 | .outputOption('-tune stillimage') |
419 | .outputOption('-shortest') | |
420 | ||
421 | return command | |
422 | } | |
423 | ||
daf6e480 | 424 | function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) { |
a1587156 | 425 | command = presetOnlyAudio(command) |
5c7d6508 | 426 | |
427 | return command | |
428 | } | |
429 | ||
a1587156 C |
430 | function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) { |
431 | command = presetCopy(command) | |
536598cf C |
432 | |
433 | command = command.outputOption('-map_metadata -1') // strip all metadata | |
434 | .outputOption('-movflags faststart') | |
435 | ||
436 | return command | |
437 | } | |
438 | ||
2650d6d4 C |
439 | function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) { |
440 | return command.outputOption('-hls_time 4') | |
441 | .outputOption('-hls_list_size 0') | |
442 | .outputOption('-hls_playlist_type vod') | |
443 | .outputOption('-hls_segment_filename ' + outputPath) | |
444 | .outputOption('-hls_segment_type fmp4') | |
445 | .outputOption('-f hls') | |
446 | .outputOption('-hls_flags single_file') | |
447 | } | |
448 | ||
c6c0fa6c | 449 | async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) { |
14aed608 C |
450 | const videoPath = getHLSVideoPath(options) |
451 | ||
a1587156 | 452 | if (options.copyCodecs) command = presetCopy(command) |
1c320673 | 453 | else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command) |
9252a33d | 454 | else command = await buildx264VODCommand(command, options) |
14aed608 | 455 | |
2650d6d4 C |
456 | addCommonHLSVODCommandOptions(command, videoPath) |
457 | ||
458 | return command | |
459 | } | |
460 | ||
461 | async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) { | |
462 | const videoPath = getHLSVideoPath(options) | |
463 | ||
3851e732 | 464 | command.outputOption('-c copy') |
e772bdf1 C |
465 | |
466 | if (options.isAAC) { | |
467 | // Required for example when copying an AAC stream from an MPEG-TS | |
468 | // Since it's a bitstream filter, we don't need to reencode the audio | |
469 | command.outputOption('-bsf:a aac_adtstoasc') | |
470 | } | |
2650d6d4 C |
471 | |
472 | addCommonHLSVODCommandOptions(command, videoPath) | |
14aed608 C |
473 | |
474 | return command | |
475 | } | |
476 | ||
536598cf | 477 | async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) { |
2650d6d4 | 478 | if (options.type !== 'hls' && options.type !== 'hls-from-ts') return |
7f8f8bdb | 479 | |
7f8f8bdb C |
480 | const fileContent = await readFile(options.outputPath) |
481 | ||
482 | const videoFileName = options.hlsPlaylist.videoFilename | |
483 | const videoFilePath = getHLSVideoPath(options) | |
484 | ||
536598cf | 485 | // Fix wrong mapping with some ffmpeg versions |
7f8f8bdb C |
486 | const newContent = fileContent.toString() |
487 | .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`) | |
488 | ||
489 | await writeFile(options.outputPath, newContent) | |
490 | } | |
491 | ||
2650d6d4 | 492 | function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) { |
9252a33d | 493 | return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}` |
4176e227 RK |
494 | } |
495 | ||
9252a33d C |
496 | // --------------------------------------------------------------------------- |
497 | // Transcoding presets | |
498 | // --------------------------------------------------------------------------- | |
499 | ||
529b3752 C |
500 | // Run encoder builder depending on available encoders |
501 | // Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one | |
502 | // If the default one does not exist, check the next encoder | |
5a547f69 | 503 | async function getEncoderBuilderResult (options: { |
529b3752 | 504 | streamType: 'video' | 'audio' |
5a547f69 C |
505 | input: string |
506 | ||
507 | availableEncoders: AvailableEncoders | |
508 | profile: string | |
509 | ||
510 | videoType: 'vod' | 'live' | |
511 | ||
512 | resolution: number | |
513 | fps?: number | |
514 | streamNum?: number | |
515 | }) { | |
516 | const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options | |
517 | ||
1896bca0 C |
518 | const encodersToTry = availableEncoders.encodersToTry[videoType][streamType] |
519 | const encoders = availableEncoders.available[videoType] | |
5a547f69 C |
520 | |
521 | for (const encoder of encodersToTry) { | |
1896bca0 C |
522 | if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) { |
523 | logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder) | |
524 | continue | |
525 | } | |
526 | ||
527 | if (!encoders[encoder]) { | |
528 | logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder) | |
529 | continue | |
530 | } | |
5a547f69 | 531 | |
529b3752 C |
532 | // An object containing available profiles for this encoder |
533 | const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder] | |
5a547f69 C |
534 | let builder = builderProfiles[profile] |
535 | ||
536 | if (!builder) { | |
537 | logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder) | |
538 | builder = builderProfiles.default | |
529b3752 C |
539 | |
540 | if (!builder) { | |
541 | logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder) | |
542 | continue | |
543 | } | |
5a547f69 C |
544 | } |
545 | ||
546 | const result = await builder({ input, resolution: resolution, fps, streamNum }) | |
547 | ||
548 | return { | |
549 | result, | |
550 | ||
551 | // If we don't have output options, then copy the input stream | |
552 | encoder: result.copy === true | |
553 | ? 'copy' | |
554 | : encoder | |
555 | } | |
556 | } | |
557 | ||
558 | return null | |
559 | } | |
560 | ||
3e03b961 C |
561 | async function presetVideo (options: { |
562 | command: ffmpeg.FfmpegCommand | |
563 | input: string | |
564 | transcodeOptions: TranscodeOptions | |
9252a33d | 565 | fps?: number |
3e03b961 C |
566 | scaleFilterValue?: string |
567 | }) { | |
568 | const { command, input, transcodeOptions, fps, scaleFilterValue } = options | |
569 | ||
cdf4cb9e | 570 | let localCommand = command |
4176e227 | 571 | .format('mp4') |
4176e227 | 572 | .outputOption('-movflags faststart') |
4176e227 | 573 | |
ce4a50b9 C |
574 | addDefaultEncoderGlobalParams({ command }) |
575 | ||
9252a33d | 576 | // Audio encoder |
daf6e480 | 577 | const parsedAudio = await getAudioStream(input) |
4176e227 | 578 | |
529b3752 | 579 | let streamsToProcess: StreamType[] = [ 'audio', 'video' ] |
9252a33d | 580 | |
cdf4cb9e C |
581 | if (!parsedAudio.audioStream) { |
582 | localCommand = localCommand.noAudio() | |
1896bca0 | 583 | streamsToProcess = [ 'video' ] |
9252a33d | 584 | } |
536598cf | 585 | |
5a547f69 C |
586 | for (const streamType of streamsToProcess) { |
587 | const { profile, resolution, availableEncoders } = transcodeOptions | |
588 | ||
589 | const builderResult = await getEncoderBuilderResult({ | |
590 | streamType, | |
591 | input, | |
592 | resolution, | |
593 | availableEncoders, | |
594 | profile, | |
595 | fps, | |
596 | videoType: 'vod' as 'vod' | |
597 | }) | |
9252a33d | 598 | |
5a547f69 C |
599 | if (!builderResult) { |
600 | throw new Error('No available encoder found for stream ' + streamType) | |
601 | } | |
9252a33d | 602 | |
1896bca0 C |
603 | logger.debug( |
604 | 'Apply ffmpeg params from %s for %s stream of input %s using %s profile.', | |
605 | builderResult.encoder, streamType, input, profile, builderResult | |
606 | ) | |
9252a33d | 607 | |
529b3752 | 608 | if (streamType === 'video') { |
5a547f69 | 609 | localCommand.videoCodec(builderResult.encoder) |
3e03b961 C |
610 | |
611 | if (scaleFilterValue) { | |
612 | localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`) | |
613 | } | |
529b3752 | 614 | } else if (streamType === 'audio') { |
5a547f69 | 615 | localCommand.audioCodec(builderResult.encoder) |
9252a33d | 616 | } |
3e03b961 | 617 | |
43f7a43c | 618 | applyEncoderOptions(localCommand, builderResult.result) |
5a547f69 | 619 | addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps }) |
536598cf | 620 | } |
bcf21a37 | 621 | |
cdf4cb9e | 622 | return localCommand |
4176e227 | 623 | } |
14aed608 | 624 | |
a1587156 | 625 | function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand { |
14aed608 C |
626 | return command |
627 | .format('mp4') | |
628 | .videoCodec('copy') | |
629 | .audioCodec('copy') | |
630 | } | |
5c7d6508 | 631 | |
a1587156 | 632 | function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand { |
5c7d6508 | 633 | return command |
634 | .format('mp4') | |
635 | .audioCodec('copy') | |
636 | .noVideo() | |
637 | } | |
c6c0fa6c | 638 | |
43f7a43c TLC |
639 | function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand { |
640 | return command | |
641 | .inputOptions(options.inputOptions ?? []) | |
43f7a43c TLC |
642 | .outputOptions(options.outputOptions ?? []) |
643 | } | |
644 | ||
3e03b961 C |
645 | function getScaleFilter (options: EncoderOptions): string { |
646 | if (options.scaleFilter) return options.scaleFilter.name | |
647 | ||
648 | return 'scale' | |
649 | } | |
650 | ||
9252a33d C |
651 | // --------------------------------------------------------------------------- |
652 | // Utils | |
653 | // --------------------------------------------------------------------------- | |
654 | ||
55223d65 | 655 | function getFFmpeg (input: string, type: 'live' | 'vod') { |
c6c0fa6c | 656 | // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems |
7abb6060 RK |
657 | const command = ffmpeg(input, { |
658 | niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD, | |
659 | cwd: CONFIG.STORAGE.TMP_DIR | |
660 | }) | |
c6c0fa6c | 661 | |
55223d65 C |
662 | const threads = type === 'live' |
663 | ? CONFIG.LIVE.TRANSCODING.THREADS | |
664 | : CONFIG.TRANSCODING.THREADS | |
665 | ||
666 | if (threads > 0) { | |
c6c0fa6c | 667 | // If we don't set any threads ffmpeg will chose automatically |
55223d65 | 668 | command.outputOption('-threads ' + threads) |
c6c0fa6c C |
669 | } |
670 | ||
671 | return command | |
672 | } | |
9252a33d | 673 | |
ae71acca C |
674 | function getFFmpegVersion () { |
675 | return new Promise<string>((res, rej) => { | |
676 | (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => { | |
677 | if (err) return rej(err) | |
678 | if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path')) | |
679 | ||
680 | return execPromise(`${ffmpegPath} -version`) | |
681 | .then(stdout => { | |
60f1f615 | 682 | const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/) |
ae71acca C |
683 | if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`)) |
684 | ||
60f1f615 C |
685 | // Fix ffmpeg version that does not include patch version (4.4 for example) |
686 | let version = parsed[1] | |
1ff9f1cd | 687 | if (version.match(/^\d+\.\d+$/)) { |
60f1f615 C |
688 | version += '.0' |
689 | } | |
690 | ||
691 | return res(version) | |
ae71acca C |
692 | }) |
693 | .catch(err => rej(err)) | |
694 | }) | |
695 | }) | |
696 | } | |
697 | ||
cd2c3dcd C |
698 | async function runCommand (options: { |
699 | command: ffmpeg.FfmpegCommand | |
700 | silent?: boolean // false | |
701 | job?: Job | |
702 | }) { | |
703 | const { command, silent = false, job } = options | |
704 | ||
9252a33d C |
705 | return new Promise<void>((res, rej) => { |
706 | command.on('error', (err, stdout, stderr) => { | |
cd2c3dcd C |
707 | if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr }) |
708 | ||
9252a33d C |
709 | rej(err) |
710 | }) | |
711 | ||
dd9c7929 C |
712 | command.on('end', (stdout, stderr) => { |
713 | logger.debug('FFmpeg command ended.', { stdout, stderr }) | |
714 | ||
9252a33d C |
715 | res() |
716 | }) | |
717 | ||
3b01f4c0 C |
718 | if (job) { |
719 | command.on('progress', progress => { | |
720 | if (!progress.percent) return | |
721 | ||
722 | job.progress(Math.round(progress.percent)) | |
723 | .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err })) | |
724 | }) | |
725 | } | |
726 | ||
9252a33d C |
727 | command.run() |
728 | }) | |
729 | } | |
09849603 RK |
730 | |
731 | // --------------------------------------------------------------------------- | |
732 | ||
733 | export { | |
734 | getLiveTranscodingCommand, | |
735 | getLiveMuxingCommand, | |
736 | buildStreamSuffix, | |
737 | convertWebPToJPG, | |
738 | processGIF, | |
739 | generateImageFromVideoFile, | |
740 | TranscodeOptions, | |
741 | TranscodeOptionsType, | |
742 | transcode, | |
743 | runCommand, | |
ae71acca | 744 | getFFmpegVersion, |
09849603 | 745 | |
1896bca0 C |
746 | resetSupportedEncoders, |
747 | ||
09849603 RK |
748 | // builders |
749 | buildx264VODCommand | |
750 | } |