ffmpeg-utils.ts 22.4 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'
6
import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptions, EncoderProfile, VideoResolution } from '../../shared/models/videos'
7
import { CONFIG } from '../initializers/config'
8
import { execPromise, isOdd, 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'
12
import { FilterSpecification } from 'fluent-ffmpeg'
13
import { findCommentId } from '@shared/extra-utils'
Chocobozzz's avatar
Chocobozzz committed
14

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

22
23
24
25
// ---------------------------------------------------------------------------
// Encoder options
// ---------------------------------------------------------------------------

26
type StreamType = 'audio' | 'video'
27

28
29
30
// ---------------------------------------------------------------------------
// Encoders support
// ---------------------------------------------------------------------------
31

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

39
40
  const getAvailableEncodersPromise = promisify0(ffmpeg.getAvailableEncoders)
  const availableFFmpegEncoders = await getAvailableEncodersPromise()
41

42
43
44
45
46
47
48
49
  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)
      }
    }
  }
50

51
  supportedEncoders = new Map<string, boolean>()
52

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

57
  logger.info('Built supported ffmpeg encoders.', { supportedEncoders, searchEncoders })
58

59
  return supportedEncoders
60
61
}

62
63
64
function resetSupportedEncoders () {
  supportedEncoders = undefined
}
65

66
67
68
69
70
// ---------------------------------------------------------------------------
// Image manipulation
// ---------------------------------------------------------------------------

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

74
  return runCommand({ command, silent: true })
75
76
77
78
79
}

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

87
  return runCommand({ command })
88
89
}

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

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

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

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

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

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

122
123
124
125
// ---------------------------------------------------------------------------
// Transcode meta function
// ---------------------------------------------------------------------------

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

interface BaseTranscodeOptions {
  type: TranscodeOptionsType
130

Chocobozzz's avatar
Chocobozzz committed
131
132
  inputPath: string
  outputPath: string
133
134
135
136

  availableEncoders: AvailableEncoders
  profile: string

137
  resolution: number
138

139
  isPortraitMode?: boolean
Chocobozzz's avatar
Chocobozzz committed
140
141

  job?: Job
Chocobozzz's avatar
Chocobozzz committed
142
}
Chocobozzz's avatar
Chocobozzz committed
143

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

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

155
156
  isAAC: boolean

Chocobozzz's avatar
Chocobozzz committed
157
158
159
160
161
  hlsPlaylist: {
    videoFilename: string
  }
}

Chocobozzz's avatar
Chocobozzz committed
162
163
164
165
166
167
168
169
170
171
172
173
174
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
175
176
interface OnlyAudioTranscodeOptions extends BaseTranscodeOptions {
  type: 'only-audio'
177
178
}

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

187
188
189
190
191
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
192
  'hls-from-ts': buildHLSVODFromTSCommand,
193
194
  'merge-audio': buildAudioMergeCommand,
  'only-audio': buildOnlyAudioCommand,
195
  'video': buildx264VODCommand
196
197
198
}

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

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

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

206
  await runCommand({ command, job: options.job })
207

208
  await fixHLSPlaylistIfNeeded(options)
209
210
}

211
212
213
// ---------------------------------------------------------------------------
// Live muxing/transcoding functions
// ---------------------------------------------------------------------------
214

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

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

227
  const command = getFFmpeg(input, 'live')
228
229
230

  const varStreamMap: string[] = []

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

Chocobozzz's avatar
Chocobozzz committed
240
  command.outputOption('-sc_threshold 0')
241

242
243
  addDefaultEncoderGlobalParams({ command })

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

    const baseEncoderBuilderParams = {
      input,
250

Chocobozzz's avatar
Chocobozzz committed
251
252
      availableEncoders,
      profile,
253

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

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

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

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

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

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

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

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

Chocobozzz's avatar
Chocobozzz committed
291
292
      command.outputOption('-map a:0')

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

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

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

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

304
305
  command.complexFilter(complexFilter)

306
  addDefaultLiveHLSParams(command, outPath)
307
308
309
310
311
312

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

  return command
}

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

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

321
  addDefaultLiveHLSParams(command, outPath)
322
323
324
325

  return command
}

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

  return base
}

334
335
336
337
// ---------------------------------------------------------------------------
// Default options
// ---------------------------------------------------------------------------

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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
355
356
357
358
359
360
361
362
363
364
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
365
    command.outputOption(buildStreamSuffix('-level:v', streamNum) + ' 3.1')
Chocobozzz's avatar
Chocobozzz committed
366
367
368
369
370

    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
371
      command.outputOption(buildStreamSuffix('-g:v', streamNum) + ' ' + (fps * 2))
Chocobozzz's avatar
Chocobozzz committed
372
373
    }
  }
374
375
}

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

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

387
388
389
390
391
// ---------------------------------------------------------------------------
// Transcode VOD command builders
// ---------------------------------------------------------------------------

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

395
  let scaleFilterValue: string
Chocobozzz's avatar
Chocobozzz committed
396
397

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

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

Chocobozzz's avatar
Chocobozzz committed
405
406
407
  return command
}

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

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

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

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

  return command
}

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

  return command
}

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

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

  return command
}

Chocobozzz's avatar
Chocobozzz committed
438
439
440
441
442
443
444
445
446
447
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')
}

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

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

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

  return command
}

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

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

  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
470
471

  addCommonHLSVODCommandOptions(command, videoPath)
Chocobozzz's avatar
Chocobozzz committed
472
473
474
475

  return command
}

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

  const fileContent = await readFile(options.outputPath)

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

Chocobozzz's avatar
Chocobozzz committed
484
  // Fix wrong mapping with some ffmpeg versions
Chocobozzz's avatar
Chocobozzz committed
485
486
487
488
489
490
  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
491
function getHLSVideoPath (options: HLSTranscodeOptions | HLSFromTSTranscodeOptions) {
492
  return `${dirname(options.outputPath)}/${options.hlsPlaylist.videoFilename}`
493
494
}

495
496
497
498
// ---------------------------------------------------------------------------
// Transcoding presets
// ---------------------------------------------------------------------------

499
500
501
// 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
502
async function getEncoderBuilderResult (options: {
503
  streamType: 'video' | 'audio'
Chocobozzz's avatar
Chocobozzz committed
504
505
506
507
508
509
510
511
512
513
514
515
516
  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

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

  for (const encoder of encodersToTry) {
521
522
523
524
525
526
527
528
529
    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
530

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

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

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

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

    return {
      result,

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

  return null
}

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

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

573
574
  addDefaultEncoderGlobalParams({ command })

575
  // Audio encoder
576
  const parsedAudio = await getAudioStream(input)
577

578
  let streamsToProcess: StreamType[] = [ 'audio', 'video' ]
579

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

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

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

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

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

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

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

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

Chocobozzz's avatar
Chocobozzz committed
621
  return localCommand
622
}
Chocobozzz's avatar
Chocobozzz committed
623

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

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

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

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

  return 'scale'
}

650
651
652
653
// ---------------------------------------------------------------------------
// Utils
// ---------------------------------------------------------------------------

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

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

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

  return command
}
672

Chocobozzz's avatar
Chocobozzz committed
673
674
675
676
677
678
679
680
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
681
          const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/)
Chocobozzz's avatar
Chocobozzz committed
682
683
          if (!parsed || !parsed[1]) return rej(new Error(`Could not find ffmpeg version in ${stdout}`))

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

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

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

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

708
709
710
      rej(err)
    })

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

714
715
716
      res()
    })

Chocobozzz's avatar
Chocobozzz committed
717
718
719
720
721
722
723
724
725
    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 }))
      })
    }

726
727
728
    command.run()
  })
}
729

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

735
736
737
738
739
740
741
742
743
744
745
746
747
// ---------------------------------------------------------------------------

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

750
751
  resetSupportedEncoders,

752
753
754
  // builders
  buildx264VODCommand
}