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