aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/transcoding
diff options
context:
space:
mode:
Diffstat (limited to 'server/lib/transcoding')
-rw-r--r--server/lib/transcoding/video-transcoding-profiles.ts256
-rw-r--r--server/lib/transcoding/video-transcoding.ts361
2 files changed, 617 insertions, 0 deletions
diff --git a/server/lib/transcoding/video-transcoding-profiles.ts b/server/lib/transcoding/video-transcoding-profiles.ts
new file mode 100644
index 000000000..c5ea72a5f
--- /dev/null
+++ b/server/lib/transcoding/video-transcoding-profiles.ts
@@ -0,0 +1,256 @@
1import { logger } from '@server/helpers/logger'
2import { AvailableEncoders, EncoderOptionsBuilder, getTargetBitrate, VideoResolution } from '../../../shared/models/videos'
3import { buildStreamSuffix, resetSupportedEncoders } from '../../helpers/ffmpeg-utils'
4import {
5 canDoQuickAudioTranscode,
6 ffprobePromise,
7 getAudioStream,
8 getMaxAudioBitrate,
9 getVideoFileBitrate,
10 getVideoStreamFromFile
11} from '../../helpers/ffprobe-utils'
12import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants'
13
14/**
15 *
16 * Available encoders and profiles for the transcoding jobs
17 * These functions are used by ffmpeg-utils that will get the encoders and options depending on the chosen profile
18 *
19 */
20
21// Resources:
22// * https://slhck.info/video/2017/03/01/rate-control.html
23// * https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
24
25const defaultX264VODOptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
26 const targetBitrate = await buildTargetBitrate({ input, resolution, fps })
27 if (!targetBitrate) return { outputOptions: [ ] }
28
29 return {
30 outputOptions: [
31 `-preset veryfast`,
32 `-r ${fps}`,
33 `-maxrate ${targetBitrate}`,
34 `-bufsize ${targetBitrate * 2}`
35 ]
36 }
37}
38
39const defaultX264LiveOptionsBuilder: EncoderOptionsBuilder = async ({ resolution, fps, streamNum }) => {
40 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
41
42 return {
43 outputOptions: [
44 `-preset veryfast`,
45 `${buildStreamSuffix('-r:v', streamNum)} ${fps}`,
46 `${buildStreamSuffix('-b:v', streamNum)} ${targetBitrate}`,
47 `-maxrate ${targetBitrate}`,
48 `-bufsize ${targetBitrate * 2}`
49 ]
50 }
51}
52
53const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input, streamNum }) => {
54 const probe = await ffprobePromise(input)
55
56 if (await canDoQuickAudioTranscode(input, probe)) {
57 logger.debug('Copy audio stream %s by AAC encoder.', input)
58 return { copy: true, outputOptions: [ ] }
59 }
60
61 const parsedAudio = await getAudioStream(input, probe)
62
63 // We try to reduce the ceiling bitrate by making rough matches of bitrates
64 // Of course this is far from perfect, but it might save some space in the end
65
66 const audioCodecName = parsedAudio.audioStream['codec_name']
67
68 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
69
70 logger.debug('Calculating audio bitrate of %s by AAC encoder.', input, { bitrate: parsedAudio.bitrate, audioCodecName })
71
72 if (bitrate !== undefined && bitrate !== -1) {
73 return { outputOptions: [ buildStreamSuffix('-b:a', streamNum), bitrate + 'k' ] }
74 }
75
76 return { outputOptions: [ ] }
77}
78
79const defaultLibFDKAACVODOptionsBuilder: EncoderOptionsBuilder = ({ streamNum }) => {
80 return { outputOptions: [ buildStreamSuffix('-q:a', streamNum), '5' ] }
81}
82
83// Used to get and update available encoders
84class VideoTranscodingProfilesManager {
85 private static instance: VideoTranscodingProfilesManager
86
87 // 1 === less priority
88 private readonly encodersPriorities = {
89 vod: this.buildDefaultEncodersPriorities(),
90 live: this.buildDefaultEncodersPriorities()
91 }
92
93 private readonly availableEncoders = {
94 vod: {
95 libx264: {
96 default: defaultX264VODOptionsBuilder
97 },
98 aac: {
99 default: defaultAACOptionsBuilder
100 },
101 libfdk_aac: {
102 default: defaultLibFDKAACVODOptionsBuilder
103 }
104 },
105 live: {
106 libx264: {
107 default: defaultX264LiveOptionsBuilder
108 },
109 aac: {
110 default: defaultAACOptionsBuilder
111 }
112 }
113 }
114
115 private availableProfiles = {
116 vod: [] as string[],
117 live: [] as string[]
118 }
119
120 private constructor () {
121 this.buildAvailableProfiles()
122 }
123
124 getAvailableEncoders (): AvailableEncoders {
125 return {
126 available: this.availableEncoders,
127 encodersToTry: {
128 vod: {
129 video: this.getEncodersByPriority('vod', 'video'),
130 audio: this.getEncodersByPriority('vod', 'audio')
131 },
132 live: {
133 video: this.getEncodersByPriority('live', 'video'),
134 audio: this.getEncodersByPriority('live', 'audio')
135 }
136 }
137 }
138 }
139
140 getAvailableProfiles (type: 'vod' | 'live') {
141 return this.availableProfiles[type]
142 }
143
144 addProfile (options: {
145 type: 'vod' | 'live'
146 encoder: string
147 profile: string
148 builder: EncoderOptionsBuilder
149 }) {
150 const { type, encoder, profile, builder } = options
151
152 const encoders = this.availableEncoders[type]
153
154 if (!encoders[encoder]) encoders[encoder] = {}
155 encoders[encoder][profile] = builder
156
157 this.buildAvailableProfiles()
158 }
159
160 removeProfile (options: {
161 type: 'vod' | 'live'
162 encoder: string
163 profile: string
164 }) {
165 const { type, encoder, profile } = options
166
167 delete this.availableEncoders[type][encoder][profile]
168 this.buildAvailableProfiles()
169 }
170
171 addEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
172 this.encodersPriorities[type][streamType].push({ name: encoder, priority })
173
174 resetSupportedEncoders()
175 }
176
177 removeEncoderPriority (type: 'vod' | 'live', streamType: 'audio' | 'video', encoder: string, priority: number) {
178 this.encodersPriorities[type][streamType] = this.encodersPriorities[type][streamType]
179 .filter(o => o.name !== encoder && o.priority !== priority)
180
181 resetSupportedEncoders()
182 }
183
184 private getEncodersByPriority (type: 'vod' | 'live', streamType: 'audio' | 'video') {
185 return this.encodersPriorities[type][streamType]
186 .sort((e1, e2) => {
187 if (e1.priority > e2.priority) return -1
188 else if (e1.priority === e2.priority) return 0
189
190 return 1
191 })
192 .map(e => e.name)
193 }
194
195 private buildAvailableProfiles () {
196 for (const type of [ 'vod', 'live' ]) {
197 const result = new Set()
198
199 const encoders = this.availableEncoders[type]
200
201 for (const encoderName of Object.keys(encoders)) {
202 for (const profile of Object.keys(encoders[encoderName])) {
203 result.add(profile)
204 }
205 }
206
207 this.availableProfiles[type] = Array.from(result)
208 }
209
210 logger.debug('Available transcoding profiles built.', { availableProfiles: this.availableProfiles })
211 }
212
213 private buildDefaultEncodersPriorities () {
214 return {
215 video: [
216 { name: 'libx264', priority: 100 }
217 ],
218
219 // Try the first one, if not available try the second one etc
220 audio: [
221 // we favor VBR, if a good AAC encoder is available
222 { name: 'libfdk_aac', priority: 200 },
223 { name: 'aac', priority: 100 }
224 ]
225 }
226 }
227
228 static get Instance () {
229 return this.instance || (this.instance = new this())
230 }
231}
232
233// ---------------------------------------------------------------------------
234
235export {
236 VideoTranscodingProfilesManager
237}
238
239// ---------------------------------------------------------------------------
240async function buildTargetBitrate (options: {
241 input: string
242 resolution: VideoResolution
243 fps: number
244}) {
245 const { input, resolution, fps } = options
246 const probe = await ffprobePromise(input)
247
248 const videoStream = await getVideoStreamFromFile(input, probe)
249 if (!videoStream) return undefined
250
251 const targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
252
253 // Don't transcode to an higher bitrate than the original file
254 const fileBitrate = await getVideoFileBitrate(input, probe)
255 return Math.min(targetBitrate, fileBitrate)
256}
diff --git a/server/lib/transcoding/video-transcoding.ts b/server/lib/transcoding/video-transcoding.ts
new file mode 100644
index 000000000..1ad63baf3
--- /dev/null
+++ b/server/lib/transcoding/video-transcoding.ts
@@ -0,0 +1,361 @@
1import { Job } from 'bull'
2import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
3import { basename, extname as extnameUtil, join } from 'path'
4import { toEven } from '@server/helpers/core-utils'
5import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
6import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
7import { VideoResolution } from '../../../shared/models/videos'
8import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
9import { transcode, TranscodeOptions, TranscodeOptionsType } from '../../helpers/ffmpeg-utils'
10import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../../helpers/ffprobe-utils'
11import { logger } from '../../helpers/logger'
12import { CONFIG } from '../../initializers/config'
13import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../../initializers/constants'
14import { VideoFileModel } from '../../models/video/video-file'
15import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
16import { updateMasterHLSPlaylist, updateSha256VODSegments } from '../hls'
17import { generateVideoFilename, generateVideoStreamingPlaylistName, getVideoFilePath } from '../video-paths'
18import { VideoTranscodingProfilesManager } from './video-transcoding-profiles'
19
20/**
21 *
22 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
23 * Mainly called by the job queue
24 *
25 */
26
27// Optimize the original video file and replace it. The resolution is not changed.
28async function optimizeOriginalVideofile (video: MVideoFullLight, inputVideoFile: MVideoFile, job?: Job) {
29 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
30 const newExtname = '.mp4'
31
32 const videoInputPath = getVideoFilePath(video, inputVideoFile)
33 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
34
35 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
36 ? 'quick-transcode'
37 : 'video'
38
39 const resolution = toEven(inputVideoFile.resolution)
40
41 const transcodeOptions: TranscodeOptions = {
42 type: transcodeType,
43
44 inputPath: videoInputPath,
45 outputPath: videoTranscodedPath,
46
47 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
48 profile: CONFIG.TRANSCODING.PROFILE,
49
50 resolution,
51
52 job
53 }
54
55 // Could be very long!
56 await transcode(transcodeOptions)
57
58 try {
59 await remove(videoInputPath)
60
61 // Important to do this before getVideoFilename() to take in account the new filename
62 inputVideoFile.extname = newExtname
63 inputVideoFile.filename = generateVideoFilename(video, false, resolution, newExtname)
64
65 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
66
67 await onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
68
69 return transcodeType
70 } catch (err) {
71 // Auto destruction...
72 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
73
74 throw err
75 }
76}
77
78// Transcode the original video file to a lower resolution.
79async function transcodeNewWebTorrentResolution (video: MVideoFullLight, resolution: VideoResolution, isPortrait: boolean, job: Job) {
80 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
81 const extname = '.mp4'
82
83 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
84 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
85
86 const newVideoFile = new VideoFileModel({
87 resolution,
88 extname,
89 filename: generateVideoFilename(video, false, resolution, extname),
90 size: 0,
91 videoId: video.id
92 })
93
94 const videoOutputPath = getVideoFilePath(video, newVideoFile)
95 const videoTranscodedPath = join(transcodeDirectory, newVideoFile.filename)
96
97 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
98 ? {
99 type: 'only-audio' as 'only-audio',
100
101 inputPath: videoInputPath,
102 outputPath: videoTranscodedPath,
103
104 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
105 profile: CONFIG.TRANSCODING.PROFILE,
106
107 resolution,
108
109 job
110 }
111 : {
112 type: 'video' as 'video',
113 inputPath: videoInputPath,
114 outputPath: videoTranscodedPath,
115
116 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
117 profile: CONFIG.TRANSCODING.PROFILE,
118
119 resolution,
120 isPortraitMode: isPortrait,
121
122 job
123 }
124
125 await transcode(transcodeOptions)
126
127 return onWebTorrentVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
128}
129
130// Merge an image with an audio file to create a video
131async function mergeAudioVideofile (video: MVideoFullLight, resolution: VideoResolution, job: Job) {
132 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
133 const newExtname = '.mp4'
134
135 const inputVideoFile = video.getMinQualityFile()
136
137 const audioInputPath = getVideoFilePath(video, inputVideoFile)
138 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
139
140 // If the user updates the video preview during transcoding
141 const previewPath = video.getPreview().getPath()
142 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
143 await copyFile(previewPath, tmpPreviewPath)
144
145 const transcodeOptions = {
146 type: 'merge-audio' as 'merge-audio',
147
148 inputPath: tmpPreviewPath,
149 outputPath: videoTranscodedPath,
150
151 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
152 profile: CONFIG.TRANSCODING.PROFILE,
153
154 audioPath: audioInputPath,
155 resolution,
156
157 job
158 }
159
160 try {
161 await transcode(transcodeOptions)
162
163 await remove(audioInputPath)
164 await remove(tmpPreviewPath)
165 } catch (err) {
166 await remove(tmpPreviewPath)
167 throw err
168 }
169
170 // Important to do this before getVideoFilename() to take in account the new file extension
171 inputVideoFile.extname = newExtname
172 inputVideoFile.filename = generateVideoFilename(video, false, inputVideoFile.resolution, newExtname)
173
174 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
175 // ffmpeg generated a new video file, so update the video duration
176 // See https://trac.ffmpeg.org/ticket/5456
177 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
178 await video.save()
179
180 return onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
181}
182
183// Concat TS segments from a live video to a fragmented mp4 HLS playlist
184async function generateHlsPlaylistResolutionFromTS (options: {
185 video: MVideoFullLight
186 concatenatedTsFilePath: string
187 resolution: VideoResolution
188 isPortraitMode: boolean
189 isAAC: boolean
190}) {
191 return generateHlsPlaylistCommon({
192 video: options.video,
193 resolution: options.resolution,
194 isPortraitMode: options.isPortraitMode,
195 inputPath: options.concatenatedTsFilePath,
196 type: 'hls-from-ts' as 'hls-from-ts',
197 isAAC: options.isAAC
198 })
199}
200
201// Generate an HLS playlist from an input file, and update the master playlist
202function generateHlsPlaylistResolution (options: {
203 video: MVideoFullLight
204 videoInputPath: string
205 resolution: VideoResolution
206 copyCodecs: boolean
207 isPortraitMode: boolean
208 job?: Job
209}) {
210 return generateHlsPlaylistCommon({
211 video: options.video,
212 resolution: options.resolution,
213 copyCodecs: options.copyCodecs,
214 isPortraitMode: options.isPortraitMode,
215 inputPath: options.videoInputPath,
216 type: 'hls' as 'hls',
217 job: options.job
218 })
219}
220
221// ---------------------------------------------------------------------------
222
223export {
224 generateHlsPlaylistResolution,
225 generateHlsPlaylistResolutionFromTS,
226 optimizeOriginalVideofile,
227 transcodeNewWebTorrentResolution,
228 mergeAudioVideofile
229}
230
231// ---------------------------------------------------------------------------
232
233async function onWebTorrentVideoFileTranscoding (
234 video: MVideoFullLight,
235 videoFile: MVideoFile,
236 transcodingPath: string,
237 outputPath: string
238) {
239 const stats = await stat(transcodingPath)
240 const fps = await getVideoFileFPS(transcodingPath)
241 const metadata = await getMetadataFromFile(transcodingPath)
242
243 await move(transcodingPath, outputPath, { overwrite: true })
244
245 videoFile.size = stats.size
246 videoFile.fps = fps
247 videoFile.metadata = metadata
248
249 await createTorrentAndSetInfoHash(video, videoFile)
250
251 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
252 video.VideoFiles = await video.$get('VideoFiles')
253
254 return video
255}
256
257async function generateHlsPlaylistCommon (options: {
258 type: 'hls' | 'hls-from-ts'
259 video: MVideoFullLight
260 inputPath: string
261 resolution: VideoResolution
262 copyCodecs?: boolean
263 isAAC?: boolean
264 isPortraitMode: boolean
265
266 job?: Job
267}) {
268 const { type, video, inputPath, resolution, copyCodecs, isPortraitMode, isAAC, job } = options
269 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
270
271 const videoTranscodedBasePath = join(transcodeDirectory, type)
272 await ensureDir(videoTranscodedBasePath)
273
274 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
275 const playlistFilename = VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution)
276 const playlistFileTranscodePath = join(videoTranscodedBasePath, playlistFilename)
277
278 const transcodeOptions = {
279 type,
280
281 inputPath,
282 outputPath: playlistFileTranscodePath,
283
284 availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
285 profile: CONFIG.TRANSCODING.PROFILE,
286
287 resolution,
288 copyCodecs,
289 isPortraitMode,
290
291 isAAC,
292
293 hlsPlaylist: {
294 videoFilename
295 },
296
297 job
298 }
299
300 await transcode(transcodeOptions)
301
302 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
303
304 // Create or update the playlist
305 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
306 videoId: video.id,
307 playlistUrl,
308 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
309 p2pMediaLoaderInfohashes: [],
310 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
311
312 type: VideoStreamingPlaylistType.HLS
313 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
314 videoStreamingPlaylist.Video = video
315
316 // Build the new playlist file
317 const extname = extnameUtil(videoFilename)
318 const newVideoFile = new VideoFileModel({
319 resolution,
320 extname,
321 size: 0,
322 filename: generateVideoFilename(video, true, resolution, extname),
323 fps: -1,
324 videoStreamingPlaylistId: videoStreamingPlaylist.id
325 })
326
327 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
328
329 // Move files from tmp transcoded directory to the appropriate place
330 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
331 await ensureDir(baseHlsDirectory)
332
333 // Move playlist file
334 const playlistPath = join(baseHlsDirectory, playlistFilename)
335 await move(playlistFileTranscodePath, playlistPath, { overwrite: true })
336 // Move video file
337 await move(join(videoTranscodedBasePath, videoFilename), videoFilePath, { overwrite: true })
338
339 const stats = await stat(videoFilePath)
340
341 newVideoFile.size = stats.size
342 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
343 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
344
345 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
346
347 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
348 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
349
350 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
351 playlistUrl, videoStreamingPlaylist.VideoFiles
352 )
353 await videoStreamingPlaylist.save()
354
355 video.setHLSPlaylist(videoStreamingPlaylist)
356
357 await updateMasterHLSPlaylist(video)
358 await updateSha256VODSegments(video)
359
360 return playlistPath
361}