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