]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/video-transcoding.ts
Export encoders options in a dedicated struct
[github/Chocobozzz/PeerTube.git] / server / lib / video-transcoding.ts
... / ...
CommitLineData
1import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
2import { basename, extname as extnameUtil, join } from 'path'
3import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
5import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
6import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
7import { AvailableEncoders, EncoderOptionsBuilder, transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
8import {
9 canDoQuickTranscode,
10 getAudioStream,
11 getDurationFromVideoFile,
12 getMaxAudioBitrate,
13 getMetadataFromFile,
14 getVideoFileBitrate,
15 getVideoFileFPS
16} from '../helpers/ffprobe-utils'
17import { logger } from '../helpers/logger'
18import { CONFIG } from '../initializers/config'
19import {
20 HLS_STREAMING_PLAYLIST_DIRECTORY,
21 P2P_MEDIA_LOADER_PEER_VERSION,
22 VIDEO_TRANSCODING_FPS,
23 WEBSERVER
24} from '../initializers/constants'
25import { VideoFileModel } from '../models/video/video-file'
26import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
27import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
28import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
29
30/**
31 * Optimize the original video file and replace it. The resolution is not changed.
32 */
33async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
34 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
35 const newExtname = '.mp4'
36
37 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
38 const videoInputPath = getVideoFilePath(video, inputVideoFile)
39 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
40
41 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
42 ? 'quick-transcode'
43 : 'video'
44
45 const transcodeOptions: TranscodeOptions = {
46 type: transcodeType,
47
48 inputPath: videoInputPath,
49 outputPath: videoTranscodedPath,
50
51 availableEncoders,
52 profile: 'default',
53
54 resolution: inputVideoFile.resolution
55 }
56
57 // Could be very long!
58 await transcode(transcodeOptions)
59
60 try {
61 await remove(videoInputPath)
62
63 // Important to do this before getVideoFilename() to take in account the new file extension
64 inputVideoFile.extname = newExtname
65
66 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
67
68 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
69 } catch (err) {
70 // Auto destruction...
71 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
72
73 throw err
74 }
75}
76
77/**
78 * Transcode the original video file to a lower resolution.
79 */
80async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
81 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
82 const extname = '.mp4'
83
84 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
85 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
86
87 const newVideoFile = new VideoFileModel({
88 resolution,
89 extname,
90 size: 0,
91 videoId: video.id
92 })
93 const videoOutputPath = getVideoFilePath(video, newVideoFile)
94 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
95
96 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
97 ? {
98 type: 'only-audio' as 'only-audio',
99
100 inputPath: videoInputPath,
101 outputPath: videoTranscodedPath,
102
103 availableEncoders,
104 profile: 'default',
105
106 resolution
107 }
108 : {
109 type: 'video' as 'video',
110 inputPath: videoInputPath,
111 outputPath: videoTranscodedPath,
112
113 availableEncoders,
114 profile: 'default',
115
116 resolution,
117 isPortraitMode: isPortrait
118 }
119
120 await transcode(transcodeOptions)
121
122 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
123}
124
125async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
126 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
127 const newExtname = '.mp4'
128
129 const inputVideoFile = video.getMinQualityFile()
130
131 const audioInputPath = getVideoFilePath(video, inputVideoFile)
132 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
133
134 // If the user updates the video preview during transcoding
135 const previewPath = video.getPreview().getPath()
136 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
137 await copyFile(previewPath, tmpPreviewPath)
138
139 const transcodeOptions = {
140 type: 'merge-audio' as 'merge-audio',
141
142 inputPath: tmpPreviewPath,
143 outputPath: videoTranscodedPath,
144
145 availableEncoders,
146 profile: 'default',
147
148 audioPath: audioInputPath,
149 resolution
150 }
151
152 try {
153 await transcode(transcodeOptions)
154
155 await remove(audioInputPath)
156 await remove(tmpPreviewPath)
157 } catch (err) {
158 await remove(tmpPreviewPath)
159 throw err
160 }
161
162 // Important to do this before getVideoFilename() to take in account the new file extension
163 inputVideoFile.extname = newExtname
164
165 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
166 // ffmpeg generated a new video file, so update the video duration
167 // See https://trac.ffmpeg.org/ticket/5456
168 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
169 await video.save()
170
171 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
172}
173
174async function generateHlsPlaylist (options: {
175 video: MVideoWithFile
176 videoInputPath: string
177 resolution: VideoResolution
178 copyCodecs: boolean
179 isPortraitMode: boolean
180}) {
181 const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options
182
183 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
184 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
185
186 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
187 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
188
189 const transcodeOptions = {
190 type: 'hls' as 'hls',
191
192 inputPath: videoInputPath,
193 outputPath,
194
195 availableEncoders,
196 profile: 'default',
197
198 resolution,
199 copyCodecs,
200 isPortraitMode,
201
202 hlsPlaylist: {
203 videoFilename
204 }
205 }
206
207 await transcode(transcodeOptions)
208
209 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
210
211 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
212 videoId: video.id,
213 playlistUrl,
214 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
215 p2pMediaLoaderInfohashes: [],
216 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
217
218 type: VideoStreamingPlaylistType.HLS
219 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
220 videoStreamingPlaylist.Video = video
221
222 const newVideoFile = new VideoFileModel({
223 resolution,
224 extname: extnameUtil(videoFilename),
225 size: 0,
226 fps: -1,
227 videoStreamingPlaylistId: videoStreamingPlaylist.id
228 })
229
230 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
231 const stats = await stat(videoFilePath)
232
233 newVideoFile.size = stats.size
234 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
235 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
236
237 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
238
239 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
240 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
241
242 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
243 playlistUrl, videoStreamingPlaylist.VideoFiles
244 )
245 await videoStreamingPlaylist.save()
246
247 video.setHLSPlaylist(videoStreamingPlaylist)
248
249 await updateMasterHLSPlaylist(video)
250 await updateSha256VODSegments(video)
251
252 return video
253}
254
255// ---------------------------------------------------------------------------
256// Available encoders profiles
257// ---------------------------------------------------------------------------
258
259const defaultX264OptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
260 if (!fps) return { outputOptions: [] }
261
262 let targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
263
264 // Don't transcode to an higher bitrate than the original file
265 const fileBitrate = await getVideoFileBitrate(input)
266 targetBitrate = Math.min(targetBitrate, fileBitrate)
267
268 return {
269 outputOptions: [
270 // Constrained Encoding (VBV)
271 // https://slhck.info/video/2017/03/01/rate-control.html
272 // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate
273 `-maxrate ${targetBitrate}`, `-bufsize ${targetBitrate * 2}`
274 ]
275 }
276}
277
278const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input }) => {
279 const parsedAudio = await getAudioStream(input)
280
281 // we try to reduce the ceiling bitrate by making rough matches of bitrates
282 // of course this is far from perfect, but it might save some space in the end
283
284 const audioCodecName = parsedAudio.audioStream['codec_name']
285
286 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
287
288 if (bitrate !== undefined && bitrate !== -1) {
289 return { outputOptions: [ '-b:a', bitrate + 'k' ] }
290 }
291
292 return { outputOptions: [] }
293}
294
295const defaultLibFDKAACOptionsBuilder: EncoderOptionsBuilder = () => {
296 return { outputOptions: [ '-aq', '5' ] }
297}
298
299const availableEncoders: AvailableEncoders = {
300 vod: {
301 libx264: {
302 default: defaultX264OptionsBuilder
303 },
304 aac: {
305 default: defaultAACOptionsBuilder
306 },
307 libfdkAAC: {
308 default: defaultLibFDKAACOptionsBuilder
309 }
310 },
311 live: {
312 libx264: {
313 default: defaultX264OptionsBuilder
314 },
315 aac: {
316 default: defaultAACOptionsBuilder
317 },
318 libfdkAAC: {
319 default: defaultLibFDKAACOptionsBuilder
320 }
321 }
322}
323
324// ---------------------------------------------------------------------------
325
326export {
327 generateHlsPlaylist,
328 optimizeOriginalVideofile,
329 transcodeNewResolution,
330 mergeAudioVideofile
331}
332
333// ---------------------------------------------------------------------------
334
335async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
336 const stats = await stat(transcodingPath)
337 const fps = await getVideoFileFPS(transcodingPath)
338 const metadata = await getMetadataFromFile(transcodingPath)
339
340 await move(transcodingPath, outputPath, { overwrite: true })
341
342 videoFile.size = stats.size
343 videoFile.fps = fps
344 videoFile.metadata = metadata
345
346 await createTorrentAndSetInfoHash(video, videoFile)
347
348 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
349 video.VideoFiles = await video.$get('VideoFiles')
350
351 return video
352}