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