]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/ffmpeg-utils.ts
Fix live replay duration glitch
[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)
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)
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
231 command.outputOption('-preset superfast')
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)
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
300 addDefaultLiveHLSParams(command, outPath)
301
302 return command
303 }
304
305 function buildStreamSuffix (base: string, streamNum?: number) {
306 if (streamNum !== undefined) {
307 return `${base}:${streamNum}`
308 }
309
310 return base
311 }
312
313 // ---------------------------------------------------------------------------
314
315 export {
316 getLiveTranscodingCommand,
317 getLiveMuxingCommand,
318 buildStreamSuffix,
319 convertWebPToJPG,
320 processGIF,
321 generateImageFromVideoFile,
322 TranscodeOptions,
323 TranscodeOptionsType,
324 transcode
325 }
326
327 // ---------------------------------------------------------------------------
328
329 // ---------------------------------------------------------------------------
330 // Default options
331 // ---------------------------------------------------------------------------
332
333 function 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
350 function 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
360 command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
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
366 command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
367 }
368 }
369 }
370
371 function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
372 command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
373 command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
374 command.outputOption('-hls_flags delete_segments')
375 command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
376 command.outputOption('-master_pl_name master.m3u8')
377 command.outputOption(`-f hls`)
378
379 command.output(join(outPath, '%v.m3u8'))
380 }
381
382 // ---------------------------------------------------------------------------
383 // Transcode VOD command builders
384 // ---------------------------------------------------------------------------
385
386 async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
387 let fps = await getVideoFileFPS(options.inputPath)
388 fps = computeFPS(fps, options.resolution)
389
390 command = await presetVideo(command, options.inputPath, options, fps)
391
392 if (options.resolution !== undefined) {
393 // '?x720' or '720x?' for example
394 const size = options.isPortraitMode === true
395 ? `${options.resolution}x?`
396 : `?x${options.resolution}`
397
398 command = command.size(size)
399 }
400
401 return command
402 }
403
404 async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
405 command = command.loop(undefined)
406
407 command = await presetVideo(command, options.audioPath, options)
408
409 command.outputOption('-preset:v veryfast')
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
419 function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
420 command = presetOnlyAudio(command)
421
422 return command
423 }
424
425 function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
426 command = presetCopy(command)
427
428 command = command.outputOption('-map_metadata -1') // strip all metadata
429 .outputOption('-movflags faststart')
430
431 return command
432 }
433
434 function 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
444 async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
445 const videoPath = getHLSVideoPath(options)
446
447 if (options.copyCodecs) command = presetCopy(command)
448 else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
449 else command = await buildx264VODCommand(command, options)
450
451 addCommonHLSVODCommandOptions(command, videoPath)
452
453 return command
454 }
455
456 async 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)
466
467 return command
468 }
469
470 async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
471 if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
472
473 const fileContent = await readFile(options.outputPath)
474
475 const videoFileName = options.hlsPlaylist.videoFilename
476 const videoFilePath = getHLSVideoPath(options)
477
478 // Fix wrong mapping with some ffmpeg versions
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
485 function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
486 return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
487 }
488
489 // ---------------------------------------------------------------------------
490 // Transcoding presets
491 // ---------------------------------------------------------------------------
492
493 async 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
536 async function presetVideo (
537 command: ffmpeg.FfmpegCommand,
538 input: string,
539 transcodeOptions: TranscodeOptions,
540 fps?: number
541 ) {
542 let localCommand = command
543 .format('mp4')
544 .outputOption('-movflags faststart')
545
546 addDefaultEncoderGlobalParams({ command })
547
548 // Audio encoder
549 const parsedAudio = await getAudioStream(input)
550
551 let streamsToProcess = [ 'AUDIO', 'VIDEO' ]
552
553 if (!parsedAudio.audioStream) {
554 localCommand = localCommand.noAudio()
555 streamsToProcess = [ 'VIDEO' ]
556 }
557
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 })
570
571 if (!builderResult) {
572 throw new Error('No available encoder found for stream ' + streamType)
573 }
574
575 logger.debug('Apply ffmpeg params from %s.', builderResult.encoder, builderResult)
576
577 if (streamType === 'VIDEO') {
578 localCommand.videoCodec(builderResult.encoder)
579 } else if (streamType === 'AUDIO') {
580 localCommand.audioCodec(builderResult.encoder)
581 }
582
583 command.addOutputOptions(builderResult.result.outputOptions)
584 addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
585 }
586
587 return localCommand
588 }
589
590 function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
591 return command
592 .format('mp4')
593 .videoCodec('copy')
594 .audioCodec('copy')
595 }
596
597 function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
598 return command
599 .format('mp4')
600 .audioCodec('copy')
601 .noVideo()
602 }
603
604 // ---------------------------------------------------------------------------
605 // Utils
606 // ---------------------------------------------------------------------------
607
608 function 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 }
619
620 async 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 }