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