aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/transcoding/video-transcoding-profiles.ts
blob: 34a364415efdcd62a49c65591a98b8421676d004 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { logger } from '@server/helpers/logger'
import { getAverageBitrate, getMinLimitBitrate } from '@shared/core-utils'
import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams, VideoResolution } from '../../../shared/models/videos'
import { buildStreamSuffix, resetSupportedEncoders } from '../../helpers/ffmpeg-utils'
import { canDoQuickAudioTranscode, ffprobePromise, getAudioStream, getMaxAudioBitrate } from '../../helpers/ffprobe-utils'

/**
 *
 * Available encoders and profiles for the transcoding jobs
 * These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
 *
 * Resources:
 *  * https://slhck.info/video/2017/03/01/rate-control.html
 *  * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
 */

const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
  const { fps, inputRatio, inputBitrate, resolution } = options
  if (!fps) return { outputOptions: [ ] }

  const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })

  return {
    outputOptions: [
      `-preset veryfast`,
      `-r ${fps}`,
      `-maxrate ${targetBitrate}`,
      `-bufsize ${targetBitrate * 2}`
    ]
  }
}

const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = (options: EncoderOptionsBuilderParams) => {
  const { streamNum, fps, inputBitrate, inputRatio, resolution } = options

  const targetBitrate = getTargetBitrate({ inputBitrate, ratio: inputRatio, fps, resolution })

  return {
    outputOptions: [
      `-preset veryfast`,
      `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
      `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
      `-maxrate ${targetBitrate}`,
      `-bufsize ${targetBitrate * 2}`
    ]
  }
}

const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
  const probe = await ffprobePromise(input)

  if (await canDoQuickAudioTranscode(input, probe)) {
    logger.debug('Copy audio stream %s by AAC encoder.', input)
    return { copy: true, outputOptions: [ ] }
  }

  const parsedAudio = await getAudioStream(input, probe)

  // We try to reduce the ceiling bitrate by making rough matches of bitrates
  // Of course this is far from perfect, but it might save some space in the end

  const audioCodecName = parsedAudio.audioStream['codec_name']

  const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)

  logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })

  if (bitrate !== -1) {
    return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
  }

  return { outputOptions: [ ] }
}

const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
  return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
}

// Used to get and update available encoders
class VideoTranscodingProfilesManager {
  private static instance: VideoTranscodingProfilesManager

  // 1 === less priority
  private readonly encodersPriorities = {
    vod: this.buildDefaultEncodersPriorities(),
    live: this.buildDefaultEncodersPriorities()
  }

  private readonly availableEncoders = {
    vod: {
      libx264: {
        default: defaultX264VODOptionsBuilder
      },
      aac: {
        default: defaultAACOptionsBuilder
      },
      libfdk_aac: {
        default: defaultLibFDKAACVODOptionsBuilder
      }
    },
    live: {
      libx264: {
        default: defaultX264LiveOptionsBuilder
      },
      aac: {
        default: defaultAACOptionsBuilder
      }
    }
  }

  private availableProfiles = {
    vod: [] as string[],
    live: [] as string[]
  }

  private constructor () {
    this.buildAvailableProfiles()
  }

  getAvailableEncoders (): AvailableEncoders {
    return {
      available: this.availableEncoders,
      encodersToTry: {
        vod: {
          video: this.getEncodersByPriority('vod', 'video'),
          audio: this.getEncodersByPriority('vod', 'audio')
        },
        live: {
          video: this.getEncodersByPriority('live', 'video'),
          audio: this.getEncodersByPriority('live', 'audio')
        }
      }
    }
  }

  getAvailableProfiles (type: 'vod' | 'live') {
    return this.availableProfiles[type]
  }

  addProfile (options: {
    type: 'vod' | 'live'
    encoder: string
    profile: string
    builder: EncoderOptionsBuilder
  }) {
    const { type, encoder, profile, builder } = options

    const encoders = this.availableEncoders[type]

    if (!encoders[encoder]) encoders[encoder] = {}
    encoders[encoder][profile] = builder

    this.buildAvailableProfiles()
  }

  removeProfile (options: {
    type: 'vod' | 'live'
    encoder: string
    profile: string
  }) {
    const { type, encoder, profile } = options

    delete this.availableEncoders[type][encoder][profile]
    this.buildAvailableProfiles()
  }

  addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
    this.encodersPriorities[type][streamType].push({ name: encoder, priority })

    resetSupportedEncoders()
  }

  removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
    this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
                                                    .filter(o => o.name !== encoder && o.priority !== priority)

    resetSupportedEncoders()
  }

  private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
    return this.encodersPriorities[type][streamType]
      .sort((e1, e2) => {
        if (e1.priority > e2.priority) return -1
        else if (e1.priority === e2.priority) return 0

        return 1
      })
      .map(e => e.name)
  }

  private buildAvailableProfiles () {
    for (const type of [ 'vod', 'live' ]) {
      const result = new Set()

      const encoders = this.availableEncoders[type]

      for (const encoderName of Object.keys(encoders)) {
        for (const profile of Object.keys(encoders[encoderName])) {
          result.add(profile)
        }
      }

      this.availableProfiles[type] = Array.from(result)
    }

    logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
  }

  private buildDefaultEncodersPriorities () {
    return {
      video: [
        { name: 'libx264', priority: 100 }
      ],

      // Try the first one, if not available try the second one etc
      audio: [
        // we favor VBR, if a good AAC encoder is available
        { name: 'libfdk_aac', priority: 200 },
        { name: 'aac', priority: 100 }
      ]
    }
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

// ---------------------------------------------------------------------------

export {
  VideoTranscodingProfilesManager
}

// ---------------------------------------------------------------------------

function getTargetBitrate (options: {
  inputBitrate: number
  resolution: VideoResolution
  ratio: number
  fps: number
}) {
  const { inputBitrate, resolution, ratio, fps } = options

  const capped = capBitrate(inputBitrate, getAverageBitrate({ resolution, fps, ratio }))
  const limit = getMinLimitBitrate({ resolution, fps, ratio })

  return Math.max(limit, capped)
}

function capBitrate (inputBitrate: number, targetBitrate: number) {
  if (!inputBitrate) return targetBitrate

  // Add 30% margin to input bitrate
  const inputBitrateWithMargin = inputBitrate + (inputBitrate * 0.3)

  return Math.min(targetBitrate, inputBitrateWithMargin)
}