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