]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/ffmpeg-utils.ts
9d6fe76cb97961d0c1d4cad932af607071a76020
[github/Chocobozzz/PeerTube.git] / server / helpers / ffmpeg-utils.ts
1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { readFile, remove, writeFile } from 'fs-extra'
3 import { dirname, join } from 'path'
4 import { FFMPEG_NICE, VIDEO_LIVE, VIDEO_TRANSCODING_ENCODERS } from '@server/initializers/constants'
5 import { VideoResolution } from '../../shared/models/videos'
6 import { checkFFmpegEncoders } from '../initializers/checker-before-init'
7 import { CONFIG } from '../initializers/config'
8 import { computeFPS, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
9 import { processImage } from './image-utils'
10 import { logger } from './logger'
11
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
19 // ---------------------------------------------------------------------------
20 // Encoder options
21 // ---------------------------------------------------------------------------
22
23 // Options builders
24
25 export type EncoderOptionsBuilder = (params: {
26 input: string
27 resolution: VideoResolution
28 fps?: number
29 streamNum?: number
30 }) => Promise<EncoderOptions> | EncoderOptions
31
32 // Options types
33
34 export interface EncoderOptions {
35 copy?: boolean
36 outputOptions: string[]
37 }
38
39 // All our encoders
40
41 export interface EncoderProfile <T> {
42 [ profile: string ]: T
43
44 default: T
45 }
46
47 export type AvailableEncoders = {
48 [ id in 'live' | 'vod' ]: {
49 [ encoder in 'libx264' | 'aac' | 'libfdk_aac' ]?: EncoderProfile<EncoderOptionsBuilder>
50 }
51 }
52
53 // ---------------------------------------------------------------------------
54 // Image manipulation
55 // ---------------------------------------------------------------------------
56
57 function convertWebPToJPG (path: string, destination: string): Promise<void> {
58 const command = ffmpeg(path)
59 .output(destination)
60
61 return runCommand(command)
62 }
63
64 function processGIF (
65 path: string,
66 destination: string,
67 newSize: { width: number, height: number }
68 ): Promise<void> {
69 const command = ffmpeg(path)
70 .fps(20)
71 .size(`${newSize.width}x${newSize.height}`)
72 .output(destination)
73
74 return runCommand(command)
75 }
76
77 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
78 const pendingImageName = 'pending-' + imageName
79
80 const options = {
81 filename: pendingImageName,
82 count: 1,
83 folder
84 }
85
86 const pendingImagePath = join(folder, pendingImageName)
87
88 try {
89 await new Promise<string>((res, rej) => {
90 ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
91 .on('error', rej)
92 .on('end', () => res(imageName))
93 .thumbnail(options)
94 })
95
96 const destination = join(folder, imageName)
97 await processImage(pendingImagePath, destination, size)
98 } catch (err) {
99 logger.error('Cannot generate image from video %s.', fromPath, { err })
100
101 try {
102 await remove(pendingImagePath)
103 } catch (err) {
104 logger.debug('Cannot remove pending image path after generation error.', { err })
105 }
106 }
107 }
108
109 // ---------------------------------------------------------------------------
110 // Transcode meta function
111 // ---------------------------------------------------------------------------
112
113 type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
114
115 interface BaseTranscodeOptions {
116 type: TranscodeOptionsType
117
118 inputPath: string
119 outputPath: string
120
121 availableEncoders: AvailableEncoders
122 profile: string
123
124 resolution: VideoResolution
125
126 isPortraitMode?: boolean
127 }
128
129 interface HLSTranscodeOptions extends BaseTranscodeOptions {
130 type: 'hls'
131 copyCodecs: boolean
132 hlsPlaylist: {
133 videoFilename: string
134 }
135 }
136
137 interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
138 type: 'hls-from-ts'
139
140 hlsPlaylist: {
141 videoFilename: string
142 }
143 }
144
145 interface QuickTranscodeOptions extends BaseTranscodeOptions {
146 type: 'quick-transcode'
147 }
148
149 interface VideoTranscodeOptions extends BaseTranscodeOptions {
150 type: 'video'
151 }
152
153 interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
154 type: 'merge-audio'
155 audioPath: string
156 }
157
158 interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
159 type: 'only-audio'
160 }
161
162 type TranscodeOptions =
163 HLSTranscodeOptions
164 | HLSFromTSTranscodeOptions
165 | VideoTranscodeOptions
166 | MergeAudioTranscodeOptions
167 | OnlyAudioTranscodeOptions
168 | QuickTranscodeOptions
169
170 const builders: {
171 [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
172 } = {
173 'quick-transcode': buildQuickTranscodeCommand,
174 'hls': buildHLSVODCommand,
175 'hls-from-ts': buildHLSVODFromTSCommand,
176 'merge-audio': buildAudioMergeCommand,
177 'only-audio': buildOnlyAudioCommand,
178 'video': buildx264VODCommand
179 }
180
181 async function transcode (options: TranscodeOptions) {
182 logger.debug('Will run transcode.', { options })
183
184 let command = getFFmpeg(options.inputPath, 'vod')
185 .output(options.outputPath)
186
187 command = await builders[options.type](command, options)
188
189 await runCommand(command)
190
191 await fixHLSPlaylistIfNeeded(options)
192 }
193
194 // ---------------------------------------------------------------------------
195 // Live muxing/transcoding functions
196 // ---------------------------------------------------------------------------
197
198 async function getLiveTranscodingCommand (options: {
199 rtmpUrl: string
200 outPath: string
201 resolutions: number[]
202 fps: number
203
204 availableEncoders: AvailableEncoders
205 profile: string
206 }) {
207 const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
208 const input = rtmpUrl
209
210 const command = getFFmpeg(input, 'live')
211
212 const varStreamMap: string[] = []
213
214 command.complexFilter([
215 {
216 inputs: '[v:0]',
217 filter: 'split',
218 options: resolutions.length,
219 outputs: resolutions.map(r => `vtemp${r}`)
220 },
221
222 ...resolutions.map(r => ({
223 inputs: `vtemp${r}`,
224 filter: 'scale',
225 options: `w=-2:h=${r}`,
226 outputs: `vout${r}`
227 }))
228 ])
229
230 command.outputOption('-preset superfast')
231 command.outputOption('-sc_threshold 0')
232
233 addDefaultEncoderGlobalParams({ command })
234
235 for (let i = 0; i < resolutions.length; i++) {
236 const resolution = resolutions[i]
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 }
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
257 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
258
259 logger.debug('Apply ffmpeg live video params from %s.', builderResult.encoder, builderResult)
260
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 }
270
271 command.outputOption('-map a:0')
272
273 addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
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 }
280
281 varStreamMap.push(`v:${i},a:${i}`)
282 }
283
284 addDefaultLiveHLSParams(command, outPath)
285
286 command.outputOption('-var_stream_map', varStreamMap.join(' '))
287
288 return command
289 }
290
291 function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
292 const command = getFFmpeg(rtmpUrl, 'live')
293
294 command.outputOption('-c:v copy')
295 command.outputOption('-c:a copy')
296 command.outputOption('-map 0:a?')
297 command.outputOption('-map 0:v?')
298
299 addDefaultLiveHLSParams(command, outPath)
300
301 return command
302 }
303
304 function buildStreamSuffix (base: string, streamNum?: number) {
305 if (streamNum !== undefined) {
306 return `${base}:${streamNum}`
307 }
308
309 return base
310 }
311
312 // ---------------------------------------------------------------------------
313
314 export {
315 getLiveTranscodingCommand,
316 getLiveMuxingCommand,
317 buildStreamSuffix,
318 convertWebPToJPG,
319 processGIF,
320 generateImageFromVideoFile,
321 TranscodeOptions,
322 TranscodeOptionsType,
323 transcode
324 }
325
326 // ---------------------------------------------------------------------------
327
328 // ---------------------------------------------------------------------------
329 // Default options
330 // ---------------------------------------------------------------------------
331
332 function addDefaultEncoderGlobalParams (options: {
333 command: ffmpeg.FfmpegCommand
334 }) {
335 const { command } = options
336
337 // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
338 command.outputOption('-max_muxing_queue_size 1024')
339 // strip all metadata
340 .outputOption('-map_metadata -1')
341 // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
342 .outputOption('-b_strategy 1')
343 // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
344 .outputOption('-bf 16')
345 // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
346 .outputOption('-pix_fmt yuv420p')
347 }
348
349 function addDefaultEncoderParams (options: {
350 command: ffmpeg.FfmpegCommand
351 encoder: 'libx264' | string
352 streamNum?: number
353 fps?: number
354 }) {
355 const { command, encoder, fps, streamNum } = options
356
357 if (encoder === 'libx264') {
358 // 3.1 is the minimal resource allocation for our highest supported resolution
359 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
360
361 if (fps) {
362 // Keyframe interval of 2 seconds for faster seeking and resolution switching.
363 // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
364 // https://superuser.com/a/908325
365 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
366 }
367 }
368 }
369
370 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
371 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
372 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
373 command.outputOption('-hls_flags delete_segments+independent_segments')
374 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
375 command.outputOption('-master_pl_name master.m3u8')
376 command.outputOption(`-f hls`)
377
378 command.output(join(outPath, '%v.m3u8'))
379 }
380
381 // ---------------------------------------------------------------------------
382 // Transcode VOD command builders
383 // ---------------------------------------------------------------------------
384
385 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
386 let fps = await getVideoFileFPS(options.inputPath)
387 fps = computeFPS(fps, options.resolution)
388
389 command = await presetVideo(command, options.inputPath, options, fps)
390
391 if (options.resolution !== undefined) {
392 // '?x720' or '720x?' for example
393 const size = options.isPortraitMode === true
394 ? `${options.resolution}x?`
395 : `?x${options.resolution}`
396
397 command = command.size(size)
398 }
399
400 return command
401 }
402
403 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
404 command = command.loop(undefined)
405
406 command = await presetVideo(command, options.audioPath, options)
407
408 command.outputOption('-preset:v veryfast')
409
410 command = command.input(options.audioPath)
411 .videoFilter('scale=trunc(iw/2)*2:trunc(ih/2)*2') // Avoid "height not divisible by 2" error
412 .outputOption('-tune stillimage')
413 .outputOption('-shortest')
414
415 return command
416 }
417
418 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
419 command = presetOnlyAudio(command)
420
421 return command
422 }
423
424 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
425 command = presetCopy(command)
426
427 command = command.outputOption('-map_metadata -1') // strip all metadata
428 .outputOption('-movflags faststart')
429
430 return command
431 }
432
433 function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
434 return command.outputOption('-hls_time 4')
435 .outputOption('-hls_list_size 0')
436 .outputOption('-hls_playlist_type vod')
437 .outputOption('-hls_segment_filename ' + outputPath)
438 .outputOption('-hls_segment_type fmp4')
439 .outputOption('-f hls')
440 .outputOption('-hls_flags single_file')
441 }
442
443 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
444 const videoPath = getHLSVideoPath(options)
445
446 if (options.copyCodecs) command = presetCopy(command)
447 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
448 else command = await buildx264VODCommand(command, options)
449
450 addCommonHLSVODCommandOptions(command, videoPath)
451
452 return command
453 }
454
455 async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
456 const videoPath = getHLSVideoPath(options)
457
458 command.outputOption('-c copy')
459 // Required for example when copying an AAC stream from an MPEG-TS
460 // Since it's a bitstream filter, we don't need to reencode the audio
461 command.outputOption('-bsf:a aac_adtstoasc')
462
463 addCommonHLSVODCommandOptions(command, videoPath)
464
465 return command
466 }
467
468 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
469 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
470
471 const fileContent = await readFile(options.outputPath)
472
473 const videoFileName = options.hlsPlaylist.videoFilename
474 const videoFilePath = getHLSVideoPath(options)
475
476 // Fix wrong mapping with some ffmpeg versions
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
483 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
484 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
485 }
486
487 // ---------------------------------------------------------------------------
488 // Transcoding presets
489 // ---------------------------------------------------------------------------
490
491 async 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
534 async function presetVideo (
535 command: ffmpeg.FfmpegCommand,
536 input: string,
537 transcodeOptions: TranscodeOptions,
538 fps?: number
539 ) {
540 let localCommand = command
541 .format('mp4')
542 .outputOption('-movflags faststart')
543
544 addDefaultEncoderGlobalParams({ command })
545
546 // Audio encoder
547 const parsedAudio = await getAudioStream(input)
548
549 let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
550
551 if (!parsedAudio.audioStream) {
552 localCommand = localCommand.noAudio()
553 streamsToProcess = [ 'VIDEO' ]
554 }
555
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 })
568
569 if (!builderResult) {
570 throw new Error('No available encoder found for stream ' + streamType)
571 }
572
573 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
574
575 if (streamType === 'VIDEO') {
576 localCommand.videoCodec(builderResult.encoder)
577 } else if (streamType === 'AUDIO') {
578 localCommand.audioCodec(builderResult.encoder)
579 }
580
581 command.addOutputOptions(builderResult.result.outputOptions)
582 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
583 }
584
585 return localCommand
586 }
587
588 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
589 return command
590 .format('mp4')
591 .videoCodec('copy')
592 .audioCodec('copy')
593 }
594
595 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
596 return command
597 .format('mp4')
598 .audioCodec('copy')
599 .noVideo()
600 }
601
602 // ---------------------------------------------------------------------------
603 // Utils
604 // ---------------------------------------------------------------------------
605
606 function getFFmpeg (input: string, type: 'live' | 'vod') {
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 const threads = type === 'live'
611 ? CONFIG.LIVE.TRANSCODING.THREADS
612 : CONFIG.TRANSCODING.THREADS
613
614 if (threads > 0) {
615 // If we don't set any threads ffmpeg will chose automatically
616 command.outputOption('-threads ' + threads)
617 }
618
619 return command
620 }
621
622 async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
623 return new Promise<void>((res, rej) => {
624 command.on('error', (err, stdout, stderr) => {
625 if (onEnd) onEnd()
626
627 logger.error('Error in transcoding job.', { stdout, stderr })
628 rej(err)
629 })
630
631 command.on('end', () => {
632 if (onEnd) onEnd()
633
634 res()
635 })
636
637 command.run()
638 })
639 }