ffmpeg-utils.ts 22.3 KB
Newer Older
Chocobozzz's avatar
Chocobozzz committed
1
import { Job } from 'bull'
Chocobozzz's avatar
Chocobozzz committed
2
import * as ffmpeg from 'fluent-ffmpeg'
Chocobozzz's avatar
Chocobozzz committed
3
import { readFile, remove, writeFile } from 'fs-extra'
Chocobozzz's avatar
Chocobozzz committed
4
import { dirname, join } from 'path'
5
import { FFMPEG_NICE, VIDEO_LIVE } from '@server/initializers/constants'
Chocobozzz's avatar
Chocobozzz committed
6
import { AvailableEncoders, EncoderOptions, EncoderOptionsBuilder, EncoderProfile, VideoResolution } from '../../shared/models/videos'
7
import { CONFIG } from '../initializers/config'
Chocobozzz's avatar
Chocobozzz committed
8
import { execPromise, promisify0 } from './core-utils'
Chocobozzz's avatar
Chocobozzz committed
9
import { computeFPS, getAudioStream, getVideoFileFPS } from './ffprobe-utils'
Chocobozzz's avatar
Chocobozzz committed
10
import { processImage } from './image-utils'
11
import { logger } from './logger'
Chocobozzz's avatar
Chocobozzz committed
12

Chocobozzz's avatar
Chocobozzz committed
13
14
15
16
17
18
19
/**
 *
 * Functions that run transcoding/muxing ffmpeg processes
 * Mainly called by lib/video-transcoding.ts and lib/live-manager.ts
 *
 */

20
21
22
23
// ---------------------------------------------------------------------------
// Encoder options
// ---------------------------------------------------------------------------

24
type StreamType = 'audio' | 'video'
25

26
27
28
// ---------------------------------------------------------------------------
// Encoders support
// ---------------------------------------------------------------------------
29

30
31
32
33
34
35
// Detect supported encoders by ffmpeg
let supportedEncoders: Map<string, boolean>
async function checkFFmpegEncoders (peertubeAvailableEncoders: AvailableEncoders): Promise<Map<string, boolean>> {
  if (supportedEncoders !== undefined) {
    return supportedEncoders
  }
36

37
38
  const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
  const availableFFmpegEncoders = await getAvailableEncodersPromise()
39

40
41
42
43
44
45
46
47
  const searchEncoders = new Set<string>()
  for (const type of [ 'live', 'vod' ]) {
    for (const streamType of [ 'audio', 'video' ]) {
      for (const encoder of peertubeAvailableEncoders.encodersToTry[type][streamType]) {
        searchEncoders.add(encoder)
      }
    }
  }
48

49
  supportedEncoders = new Map<string, boolean>()
50

51
52
  for (const searchEncoder of searchEncoders) {
    supportedEncoders.set(searchEncoder, availableFFmpegEncoders[searchEncoder] !== undefined)
53
54
  }

55
  logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
56

57
  return supportedEncoders
58
59
}

60
61
62
function resetSupportedEncoders () {
  supportedEncoders = undefined
}
63

64
65
66
67
68
// ---------------------------------------------------------------------------
// Image manipulation
// ---------------------------------------------------------------------------

function convertWebPToJPG (path: string, destination: string): Promise<void> {
69
  const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
70
71
    .output(destination)

72
  return runCommand({ command, silent: true })
73
74
75
76
77
}

function processGIF (
  path: string,
  destination: string,
Chocobozzz's avatar
Chocobozzz committed
78
  newSize: { width: number, height: number }
79
): Promise<void> {
80
  const command = ffmpeg(path, { niceness: FFMPEG_NICE.THUMBNAIL })
Chocobozzz's avatar
Chocobozzz committed
81
82
83
    .fps(20)
    .size(`${newSize.width}x${newSize.height}`)
    .output(destination)
84

85
  return runCommand({ command })
86
87
}

Chocobozzz's avatar
Chocobozzz committed
88
89
90
async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
  const pendingImageName = 'pending-' + imageName

Chocobozzz's avatar
Chocobozzz committed
91
  const options = {
Chocobozzz's avatar
Chocobozzz committed
92
    filename: pendingImageName,
Chocobozzz's avatar
Chocobozzz committed
93
94
95
96
    count: 1,
    folder
  }

Chocobozzz's avatar
Chocobozzz committed
97
  const pendingImagePath = join(folder, pendingImageName)
98
99
100

  try {
    await new Promise<string>((res, rej) => {
101
      ffmpeg(fromPath, { niceness: FFMPEG_NICE.THUMBNAIL })
102
103
104
105
106
107
        .on('error', rej)
        .on('end', () => res(imageName))
        .thumbnail(options)
    })

    const destination = join(folder, imageName)
108
    await processImage(pendingImagePath, destination, size)
109
  } catch (err) {
Chocobozzz's avatar
Chocobozzz committed
110
    logger.error('Cannot generate image from video %s.', fromPath, { err })
111
112

    try {
Chocobozzz's avatar
Chocobozzz committed
113
      await remove(pendingImagePath)
114
    } catch (err) {
Chocobozzz's avatar
Chocobozzz committed
115
      logger.debug('Cannot remove pending image path after generation error.', { err })
116
117
    }
  }
Chocobozzz's avatar
Chocobozzz committed
118
119
}

120
121
122
123
// ---------------------------------------------------------------------------
// Transcode meta function
// ---------------------------------------------------------------------------

Chocobozzz's avatar
Chocobozzz committed
124
type TranscodeOptionsType = 'hls' | 'hls-from-ts' | 'quick-transcode' | 'video' | 'merge-audio' | 'only-audio'
Chocobozzz's avatar
Chocobozzz committed
125
126
127

interface BaseTranscodeOptions {
  type: TranscodeOptionsType
128

Chocobozzz's avatar
Chocobozzz committed
129
130
  inputPath: string
  outputPath: string
131
132
133
134

  availableEncoders: AvailableEncoders
  profile: string

135
  resolution: number
136

137
  isPortraitMode?: boolean
Chocobozzz's avatar
Chocobozzz committed
138
139

  job?: Job
Chocobozzz's avatar
Chocobozzz committed
140
}
Chocobozzz's avatar
Chocobozzz committed
141

Chocobozzz's avatar
Chocobozzz committed
142
143
interface HLSTranscodeOptions extends BaseTranscodeOptions {
  type: 'hls'
Chocobozzz's avatar
Chocobozzz committed
144
  copyCodecs: boolean
Chocobozzz's avatar
Chocobozzz committed
145
  hlsPlaylist: {
146
147
    videoFilename: string
  }
Chocobozzz's avatar
Chocobozzz committed
148
149
}

Chocobozzz's avatar
Chocobozzz committed
150
151
152
interface HLSFromTSTranscodeOptions extends BaseTranscodeOptions {
  type: 'hls-from-ts'

153
154
  isAAC: boolean

Chocobozzz's avatar
Chocobozzz committed
155
156
157
158
159
  hlsPlaylist: {
    videoFilename: string
  }
}

Chocobozzz's avatar
Chocobozzz committed
160
161
162
163
164
165
166
167
168
169
170
171
172
interface QuickTranscodeOptions extends BaseTranscodeOptions {
  type: 'quick-transcode'
}

interface VideoTranscodeOptions extends BaseTranscodeOptions {
  type: 'video'
}

interface MergeAudioTranscodeOptions extends BaseTranscodeOptions {
  type: 'merge-audio'
  audioPath: string
}

Chocobozzz's avatar
Chocobozzz committed
173
174
interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
  type: 'only-audio'
175
176
}

Chocobozzz's avatar
Chocobozzz committed
177
178
type TranscodeOptions =
  HLSTranscodeOptions
Chocobozzz's avatar
Chocobozzz committed
179
  | HLSFromTSTranscodeOptions
Chocobozzz's avatar
Chocobozzz committed
180
181
182
183
  | VideoTranscodeOptions
  | MergeAudioTranscodeOptions
  | OnlyAudioTranscodeOptions
  | QuickTranscodeOptions
Chocobozzz's avatar
Chocobozzz committed
184

185
186
187
188
189
const builders: {
  [ type in TranscodeOptionsType ]: (c: ffmpeg.FfmpegCommand, o?: TranscodeOptions) => Promise<ffmpeg.FfmpegCommand> | ffmpeg.FfmpegCommand
} = {
  'quick-transcode': buildQuickTranscodeCommand,
  'hls': buildHLSVODCommand,
Chocobozzz's avatar
Chocobozzz committed
190
  'hls-from-ts': buildHLSVODFromTSCommand,
191
192
  'merge-audio': buildAudioMergeCommand,
  'only-audio': buildOnlyAudioCommand,
193
  'video': buildx264VODCommand
194
195
196
}

async function transcode (options: TranscodeOptions) {
197
198
  logger.debug('Will run transcode.', { options })

199
  let command = getFFmpeg(options.inputPath, 'vod')
200
    .output(options.outputPath)
Chocobozzz's avatar
Chocobozzz committed
201

202
  command = await builders[options.type](command, options)
Felix's avatar
Felix committed
203

204
  await runCommand({ command, job: options.job })
205

206
  await fixHLSPlaylistIfNeeded(options)
207
208
}

209
210
211
// ---------------------------------------------------------------------------
// Live muxing/transcoding functions
// ---------------------------------------------------------------------------
212

Chocobozzz's avatar
Chocobozzz committed
213
214
215
216
217
218
219
220
221
async function getLiveTranscodingCommand (options: {
  rtmpUrl: string
  outPath: string
  resolutions: number[]
  fps: number

  availableEncoders: AvailableEncoders
  profile: string
}) {
222
  const { rtmpUrl, outPath, resolutions, fps, availableEncoders, profile } = options
Chocobozzz's avatar
Chocobozzz committed
223
224
  const input = rtmpUrl

225
  const command = getFFmpeg(input, 'live')
226
227
228

  const varStreamMap: string[] = []

229
  const complexFilter: FilterSpecification[] = [
230
231
232
233
234
    {
      inputs: '[v:0]',
      filter: 'split',
      options: resolutions.length,
      outputs: resolutions.map(r => `vtemp${r}`)
235
236
    }
  ]
237

Chocobozzz's avatar
Chocobozzz committed
238
  command.outputOption('-sc_threshold 0')
239

240
241
  addDefaultEncoderGlobalParams({ command })

242
243
  for (let i = 0; i < resolutions.length; i++) {
    const resolution = resolutions[i]
Chocobozzz's avatar
Chocobozzz committed
244
245
246
247
    const resolutionFPS = computeFPS(fps, resolution)

    const baseEncoderBuilderParams = {
      input,
248

Chocobozzz's avatar
Chocobozzz committed
249
250
      availableEncoders,
      profile,
251

Chocobozzz's avatar
Chocobozzz committed
252
253
254
255
256
      fps: resolutionFPS,
      resolution,
      streamNum: i,
      videoType: 'live' as 'live'
    }
Chocobozzz's avatar
Chocobozzz committed
257
258

    {
259
260
      const streamType: StreamType = 'video'
      const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
Chocobozzz's avatar
Chocobozzz committed
261
262
263
264
265
266
      if (!builderResult) {
        throw new Error('No available live video encoder found')
      }

      command.outputOption(`-map [vout${resolution}]`)

Chocobozzz's avatar
Chocobozzz committed
267
      addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
Chocobozzz's avatar
Chocobozzz committed
268

269
      logger.debug('Apply ffmpeg live video params from %s using %s profile.', builderResult.encoder, profile, builderResult)
270

Chocobozzz's avatar
Chocobozzz committed
271
      command.outputOption(`${buildStreamSuffix('-c:v', i)} ${builderResult.encoder}`)
272
      applyEncoderOptions(command, builderResult.result)
273
274
275
276
277
278
279

      complexFilter.push({
        inputs: `vtemp${resolution}`,
        filter: getScaleFilter(builderResult.result),
        options: `w=-2:h=${resolution}`,
        outputs: `vout${resolution}`
      })
Chocobozzz's avatar
Chocobozzz committed
280
281
282
    }

    {
283
284
      const streamType: StreamType = 'audio'
      const builderResult = await getEncoderBuilderResult(Object.assign({}, baseEncoderBuilderParams, { streamType }))
Chocobozzz's avatar
Chocobozzz committed
285
286
287
      if (!builderResult) {
        throw new Error('No available live audio encoder found')
      }
288

Chocobozzz's avatar
Chocobozzz committed
289
290
      command.outputOption('-map a:0')

Chocobozzz's avatar
Chocobozzz committed
291
      addDefaultEncoderParams({ command, encoder: builderResult.encoder, fps: resolutionFPS, streamNum: i })
Chocobozzz's avatar
Chocobozzz committed
292

293
      logger.debug('Apply ffmpeg live audio params from %s using %s profile.', builderResult.encoder, profile, builderResult)
Chocobozzz's avatar
Chocobozzz committed
294
295

      command.outputOption(`${buildStreamSuffix('-c:a', i)} ${builderResult.encoder}`)
296
      applyEncoderOptions(command, builderResult.result)
Chocobozzz's avatar
Chocobozzz committed
297
    }
298
299
300
301

    varStreamMap.push(`v:${i},a:${i}`)
  }

302
303
  command.complexFilter(complexFilter)

304
  addDefaultLiveHLSParams(command, outPath)
305
306
307
308
309
310

  command.outputOption('-var_stream_map', varStreamMap.join(' '))

  return command
}

311
function getLiveMuxingCommand (rtmpUrl: string, outPath: string) {
312
  const command = getFFmpeg(rtmpUrl, 'live')
313
314
315
316
317
318

  command.outputOption('-c:v copy')
  command.outputOption('-c:a copy')
  command.outputOption('-map 0:a?')
  command.outputOption('-map 0:v?')

319
  addDefaultLiveHLSParams(command, outPath)
320
321
322
323

  return command
}

Chocobozzz's avatar
Chocobozzz committed
324
325
326
327
328
329
330
331
function buildStreamSuffix (base: string, streamNum?: number) {
  if (streamNum !== undefined) {
    return `${base}:${streamNum}`
  }

  return base
}

332
333
334
335
// ---------------------------------------------------------------------------
// Default options
// ---------------------------------------------------------------------------

336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
function addDefaultEncoderGlobalParams (options: {
  command: ffmpeg.FfmpegCommand
}) {
  const { command } = options

  // avoid issues when transcoding some files: https://trac.ffmpeg.org/ticket/6375
  command.outputOption('-max_muxing_queue_size 1024')
         // strip all metadata
         .outputOption('-map_metadata -1')
         // NOTE: b-strategy 1 - heuristic algorithm, 16 is optimal B-frames for it
         .outputOption('-b_strategy 1')
         // NOTE: Why 16: https://github.com/Chocobozzz/PeerTube/pull/774. b-strategy 2 -> B-frames<16
         .outputOption('-bf 16')
         // allows import of source material with incompatible pixel formats (e.g. MJPEG video)
         .outputOption('-pix_fmt yuv420p')
}

Chocobozzz's avatar
Chocobozzz committed
353
354
355
356
357
358
359
360
361
362
function addDefaultEncoderParams (options: {
  command: ffmpeg.FfmpegCommand
  encoder: 'libx264' | string
  streamNum?: number
  fps?: number
}) {
  const { command, encoder, fps, streamNum } = options

  if (encoder === 'libx264') {
    // 3.1 is the minimal resource allocation for our highest supported resolution
363
    command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
Chocobozzz's avatar
Chocobozzz committed
364
365
366
367
368

    if (fps) {
      // Keyframe interval of 2 seconds for faster seeking and resolution switching.
      // https://streaminglearningcenter.com/blogs/whats-the-right-keyframe-interval.html
      // https://superuser.com/a/908325
369
      command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
Chocobozzz's avatar
Chocobozzz committed
370
371
    }
  }
372
373
}

374
function addDefaultLiveHLSParams (command: ffmpeg.FfmpegCommand, outPath: string) {
Chocobozzz's avatar
Chocobozzz committed
375
  command.outputOption('-hls_time ' + VIDEO_LIVE.SEGMENT_TIME_SECONDS)
Chocobozzz's avatar
Chocobozzz committed
376
  command.outputOption('-hls_list_size ' + VIDEO_LIVE.SEGMENTS_LIST_SIZE)
Chocobozzz's avatar
Chocobozzz committed
377
  command.outputOption('-hls_flags delete_segments+independent_segments')
Chocobozzz's avatar
Chocobozzz committed
378
  command.outputOption(`-hls_segment_filename ${join(outPath, '%v-%06d.ts')}`)
379
380
381
382
383
384
  command.outputOption('-master_pl_name master.m3u8')
  command.outputOption(`-f hls`)

  command.output(join(outPath, '%v.m3u8'))
}

385
386
387
388
389
// ---------------------------------------------------------------------------
// Transcode VOD command builders
// ---------------------------------------------------------------------------

async function buildx264VODCommand (command: ffmpeg.FfmpegCommand, options: TranscodeOptions) {
Chocobozzz's avatar
Chocobozzz committed
390
  let fps = await getVideoFileFPS(options.inputPath)
Chocobozzz's avatar
Chocobozzz committed
391
  fps = computeFPS(fps, options.resolution)
Chocobozzz's avatar
Chocobozzz committed
392

393
  let scaleFilterValue: string
Chocobozzz's avatar
Chocobozzz committed
394
395

  if (options.resolution !== undefined) {
396
    scaleFilterValue = options.isPortraitMode === true
Chocobozzz's avatar
Chocobozzz committed
397
398
      ? `w=${options.resolution}:h=-2`
      : `w=-2:h=${options.resolution}`
Chocobozzz's avatar
Chocobozzz committed
399
400
  }

401
402
  command = await presetVideo({ command, input: options.inputPath, transcodeOptions: options, fps, scaleFilterValue })

Chocobozzz's avatar
Chocobozzz committed
403
404
405
  return command
}

Chocobozzz's avatar
Chocobozzz committed
406
407
408
async function buildAudioMergeCommand (command: ffmpeg.FfmpegCommand, options: MergeAudioTranscodeOptions) {
  command = command.loop(undefined)

409
  const scaleFilterValue = getScaleCleanerValue()
410
  command = await presetVideo({ command, input: options.audioPath, transcodeOptions: options, scaleFilterValue })
411
412

  command.outputOption('-preset:v veryfast')
Chocobozzz's avatar
Chocobozzz committed
413
414
415
416
417
418
419
420

  command = command.input(options.audioPath)
                   .outputOption('-tune stillimage')
                   .outputOption('-shortest')

  return command
}

421
function buildOnlyAudioCommand (command: ffmpeg.FfmpegCommand, _options: OnlyAudioTranscodeOptions) {
Chocobozzz's avatar
Chocobozzz committed
422
  command = presetOnlyAudio(command)
423
424
425
426

  return command
}

Chocobozzz's avatar
Chocobozzz committed
427
428
function buildQuickTranscodeCommand (command: ffmpeg.FfmpegCommand) {
  command = presetCopy(command)
Chocobozzz's avatar
Chocobozzz committed
429
430
431
432
433
434
435

  command = command.outputOption('-map_metadata -1') // strip all metadata
                   .outputOption('-movflags faststart')

  return command
}

Chocobozzz's avatar
Chocobozzz committed
436
437
438
439
440
441
442
443
444
445
function addCommonHLSVODCommandOptions (command: ffmpeg.FfmpegCommand, outputPath: string) {
  return command.outputOption('-hls_time 4')
                .outputOption('-hls_list_size 0')
                .outputOption('-hls_playlist_type vod')
                .outputOption('-hls_segment_filename ' + outputPath)
                .outputOption('-hls_segment_type fmp4')
                .outputOption('-f hls')
                .outputOption('-hls_flags single_file')
}

446
async function buildHLSVODCommand (command: ffmpeg.FfmpegCommand, options: HLSTranscodeOptions) {
Chocobozzz's avatar
Chocobozzz committed
447
448
  const videoPath = getHLSVideoPath(options)

Chocobozzz's avatar
Chocobozzz committed
449
  if (options.copyCodecs) command = presetCopy(command)
Chocobozzz's avatar
Chocobozzz committed
450
  else if (options.resolution === VideoResolution.H_NOVIDEO) command = presetOnlyAudio(command)
451
  else command = await buildx264VODCommand(command, options)
Chocobozzz's avatar
Chocobozzz committed
452

Chocobozzz's avatar
Chocobozzz committed
453
454
455
456
457
458
459
460
  addCommonHLSVODCommandOptions(command, videoPath)

  return command
}

async function buildHLSVODFromTSCommand (command: ffmpeg.FfmpegCommand, options: HLSFromTSTranscodeOptions) {
  const videoPath = getHLSVideoPath(options)

Chocobozzz's avatar
Chocobozzz committed
461
  command.outputOption('-c copy')
462
463
464
465
466
467

  if (options.isAAC) {
    // Required for example when copying an AAC stream from an MPEG-TS
    // Since it's a bitstream filter, we don't need to reencode the audio
    command.outputOption('-bsf:a aac_adtstoasc')
  }
Chocobozzz's avatar
Chocobozzz committed
468
469

  addCommonHLSVODCommandOptions(command, videoPath)
Chocobozzz's avatar
Chocobozzz committed
470
471
472
473

  return command
}

Chocobozzz's avatar
Chocobozzz committed
474
async function fixHLSPlaylistIfNeeded (options: TranscodeOptions) {
Chocobozzz's avatar
Chocobozzz committed
475
  if (options.type !== 'hls' && options.type !== 'hls-from-ts') return
Chocobozzz's avatar
Chocobozzz committed
476
477
478
479
480
481

  const fileContent = await readFile(options.outputPath)

  const videoFileName = options.hlsPlaylist.videoFilename
  const videoFilePath = getHLSVideoPath(options)

Chocobozzz's avatar
Chocobozzz committed
482
  // Fix wrong mapping with some ffmpeg versions
Chocobozzz's avatar
Chocobozzz committed
483
484
485
486
487
488
  const newContent = fileContent.toString()
                                .replace(`#EXT-X-MAP:URI="${videoFilePath}",`, `#EXT-X-MAP:URI="${videoFileName}",`)

  await writeFile(options.outputPath, newContent)
}

Chocobozzz's avatar
Chocobozzz committed
489
function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
490
  return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
491
492
}

493
494
495
496
// ---------------------------------------------------------------------------
// Transcoding presets
// ---------------------------------------------------------------------------

497
498
499
// Run encoder builder depending on available encoders
// Try encoders by priority: if the encoder is available, run the chosen profile or fallback to the default one
// If the default one does not exist, check the next encoder
Chocobozzz's avatar
Chocobozzz committed
500
async function getEncoderBuilderResult (options: {
501
  streamType: 'video' | 'audio'
Chocobozzz's avatar
Chocobozzz committed
502
503
504
505
506
507
508
509
510
511
512
513
514
  input: string

  availableEncoders: AvailableEncoders
  profile: string

  videoType: 'vod' | 'live'

  resolution: number
  fps?: number
  streamNum?: number
}) {
  const { availableEncoders, input, profile, resolution, streamType, fps, streamNum, videoType } = options

515
516
  const encodersToTry = availableEncoders.encodersToTry[videoType][streamType]
  const encoders = availableEncoders.available[videoType]
Chocobozzz's avatar
Chocobozzz committed
517
518

  for (const encoder of encodersToTry) {
519
520
521
522
523
524
525
526
527
    if (!(await checkFFmpegEncoders(availableEncoders)).get(encoder)) {
      logger.debug('Encoder %s not available in ffmpeg, skipping.', encoder)
      continue
    }

    if (!encoders[encoder]) {
      logger.debug('Encoder %s not available in peertube encoders, skipping.', encoder)
      continue
    }
Chocobozzz's avatar
Chocobozzz committed
528

529
530
    // An object containing available profiles for this encoder
    const builderProfiles: EncoderProfile<EncoderOptionsBuilder> = encoders[encoder]
Chocobozzz's avatar
Chocobozzz committed
531
532
533
534
535
    let builder = builderProfiles[profile]

    if (!builder) {
      logger.debug('Profile %s for encoder %s not available. Fallback to default.', profile, encoder)
      builder = builderProfiles.default
536
537
538
539
540

      if (!builder) {
        logger.debug('Default profile for encoder %s not available. Try next available encoder.', encoder)
        continue
      }
Chocobozzz's avatar
Chocobozzz committed
541
542
    }

543
    const result = await builder({ input, resolution, fps, streamNum })
Chocobozzz's avatar
Chocobozzz committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557

    return {
      result,

      // If we don't have output options, then copy the input stream
      encoder: result.copy === true
        ? 'copy'
        : encoder
    }
  }

  return null
}

558
559
560
561
async function presetVideo (options: {
  command: ffmpeg.FfmpegCommand
  input: string
  transcodeOptions: TranscodeOptions
562
  fps?: number
563
564
565
566
  scaleFilterValue?: string
}) {
  const { command, input, transcodeOptions, fps, scaleFilterValue } = options

Chocobozzz's avatar
Chocobozzz committed
567
  let localCommand = command
568
569
570
    .format('mp4')
    .outputOption('-movflags faststart')

571
572
  addDefaultEncoderGlobalParams({ command })

573
  // Audio encoder
574
  const parsedAudio = await getAudioStream(input)
575

576
  let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
577

Chocobozzz's avatar
Chocobozzz committed
578
579
  if (!parsedAudio.audioStream) {
    localCommand = localCommand.noAudio()
580
    streamsToProcess = [ 'video' ]
581
  }
Chocobozzz's avatar
Chocobozzz committed
582

Chocobozzz's avatar
Chocobozzz committed
583
584
585
586
587
588
589
590
591
592
593
594
  for (const streamType of streamsToProcess) {
    const { profile, resolution, availableEncoders } = transcodeOptions

    const builderResult = await getEncoderBuilderResult({
      streamType,
      input,
      resolution,
      availableEncoders,
      profile,
      fps,
      videoType: 'vod' as 'vod'
    })
595

Chocobozzz's avatar
Chocobozzz committed
596
597
598
    if (!builderResult) {
      throw new Error('No available encoder found for stream ' + streamType)
    }
599

600
601
602
603
    logger.debug(
      'Apply ffmpeg params from %s for %s stream of input %s using %s profile.',
      builderResult.encoder, streamType, input, profile, builderResult
    )
604

605
    if (streamType === 'video') {
Chocobozzz's avatar
Chocobozzz committed
606
      localCommand.videoCodec(builderResult.encoder)
607
608
609
610

      if (scaleFilterValue) {
        localCommand.outputOption(`-vf ${getScaleFilter(builderResult.result)}=${scaleFilterValue}`)
      }
611
    } else if (streamType === 'audio') {
Chocobozzz's avatar
Chocobozzz committed
612
      localCommand.audioCodec(builderResult.encoder)
613
    }
614

615
    applyEncoderOptions(localCommand, builderResult.result)
Chocobozzz's avatar
Chocobozzz committed
616
    addDefaultEncoderParams({ command: localCommand, encoder: builderResult.encoder, fps })
Chocobozzz's avatar
Chocobozzz committed
617
  }
618

Chocobozzz's avatar
Chocobozzz committed
619
  return localCommand
620
}
Chocobozzz's avatar
Chocobozzz committed
621

Chocobozzz's avatar
Chocobozzz committed
622
function presetCopy (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
Chocobozzz's avatar
Chocobozzz committed
623
624
625
626
627
  return command
    .format('mp4')
    .videoCodec('copy')
    .audioCodec('copy')
}
628

Chocobozzz's avatar
Chocobozzz committed
629
function presetOnlyAudio (command: ffmpeg.FfmpegCommand): ffmpeg.FfmpegCommand {
630
631
632
633
634
  return command
    .format('mp4')
    .audioCodec('copy')
    .noVideo()
}
635

636
637
638
639
640
641
function applyEncoderOptions (command: ffmpeg.FfmpegCommand, options: EncoderOptions): ffmpeg.FfmpegCommand {
  return command
    .inputOptions(options.inputOptions ?? [])
    .outputOptions(options.outputOptions ?? [])
}

642
643
644
645
646
647
function getScaleFilter (options: EncoderOptions): string {
  if (options.scaleFilter) return options.scaleFilter.name

  return 'scale'
}

648
649
650
651
// ---------------------------------------------------------------------------
// Utils
// ---------------------------------------------------------------------------

652
function getFFmpeg (input: string, type: 'live' | 'vod') {
653
  // We set cwd explicitly because ffmpeg appears to create temporary files when trancoding which fails in read-only file systems
654
655
656
657
  const command = ffmpeg(input, {
    niceness: type === 'live' ? FFMPEG_NICE.LIVE : FFMPEG_NICE.VOD,
    cwd: CONFIG.STORAGE.TMP_DIR
  })
658

659
660
661
662
663
  const threads = type === 'live'
    ? CONFIG.LIVE.TRANSCODING.THREADS
    : CONFIG.TRANSCODING.THREADS

  if (threads > 0) {
664
    // If we don't set any threads ffmpeg will chose automatically
665
    command.outputOption('-threads ' + threads)
666
667
668
669
  }

  return command
}
670

Chocobozzz's avatar
Chocobozzz committed
671
672
673
674
675
676
677
678
function getFFmpegVersion () {
  return new Promise<string>((res, rej) => {
    (ffmpeg() as any)._getFfmpegPath((err, ffmpegPath) => {
      if (err) return rej(err)
      if (!ffmpegPath) return rej(new Error('Could not find ffmpeg path'))

      return execPromise(`${ffmpegPath} -version`)
        .then(stdout => {
Chocobozzz's avatar
Chocobozzz committed
679
          const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
Chocobozzz's avatar
Chocobozzz committed
680
681
          if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))

Chocobozzz's avatar
Chocobozzz committed
682
683
          // Fix ffmpeg version that does not include patch version (4.4 for example)
          let version = parsed[1]
Chocobozzz's avatar
Chocobozzz committed
684
          if (version.match(/^\d+\.\d+$/)) {
Chocobozzz's avatar
Chocobozzz committed
685
686
687
688
            version += '.0'
          }

          return res(version)
Chocobozzz's avatar
Chocobozzz committed
689
690
691
692
693
694
        })
        .catch(err => rej(err))
    })
  })
}

695
696
697
698
699
700
701
async function runCommand (options: {
  command: ffmpeg.FfmpegCommand
  silent?: boolean // false
  job?: Job
}) {
  const { command, silent = false, job } = options

702
703
  return new Promise<void>((res, rej) => {
    command.on('error', (err, stdout, stderr) => {
704
705
      if (silent !== true) logger.error('Error in ffmpeg.', { stdout, stderr })

706
707
708
      rej(err)
    })

709
710
711
    command.on('end', (stdout, stderr) => {
      logger.debug('FFmpeg command ended.', { stdout, stderr })

712
713
714
      res()
    })

Chocobozzz's avatar
Chocobozzz committed
715
716
717
718
719
720
721
722
723
    if (job) {
      command.on('progress', progress => {
        if (!progress.percent) return

        job.progress(Math.round(progress.percent))
          .catch(err => logger.warn('Cannot set ffmpeg job progress.', { err }))
      })
    }

724
725
726
    command.run()
  })
}
727

728
729
730
731
732
// Avoid "height not divisible by 2" error
function getScaleCleanerValue () {
  return 'trunc(iw/2)*2:trunc(ih/2)*2'
}

733
734
735
736
737
738
739
740
741
742
743
744
745
// ---------------------------------------------------------------------------

export {
  getLiveTranscodingCommand,
  getLiveMuxingCommand,
  buildStreamSuffix,
  convertWebPToJPG,
  processGIF,
  generateImageFromVideoFile,
  TranscodeOptions,
  TranscodeOptionsType,
  transcode,
  runCommand,
Chocobozzz's avatar
Chocobozzz committed
746
  getFFmpegVersion,
747

748
749
  resetSupportedEncoders,

750
751
752
  // builders
  buildx264VODCommand
}