1 import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
2 import { basename, extname as extnameUtil, join } from 'path'
3 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
5 import { getTargetBitrate, VideoResolution } from '../../shared/models/videos'
6 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
7 import { AvailableEncoders, EncoderOptionsBuilder, transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
11 getDurationFromVideoFile,
16 } from '../helpers/ffprobe-utils'
17 import { logger } from '../helpers/logger'
18 import { CONFIG } from '../initializers/config'
20 HLS_STREAMING_PLAYLIST_DIRECTORY,
21 P2P_MEDIA_LOADER_PEER_VERSION,
22 VIDEO_TRANSCODING_FPS,
24 } from '../initializers/constants'
25 import { VideoFileModel } from '../models/video/video-file'
26 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
27 import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
28 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
31 * Optimize the original video file and replace it. The resolution is not changed.
33 async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
34 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
35 const newExtname = '.mp4'
37 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
38 const videoInputPath = getVideoFilePath(video, inputVideoFile)
39 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
41 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
45 const transcodeOptions: TranscodeOptions = {
48 inputPath: videoInputPath,
49 outputPath: videoTranscodedPath,
54 resolution: inputVideoFile.resolution
57 // Could be very long!
58 await transcode(transcodeOptions)
61 await remove(videoInputPath)
63 // Important to do this before getVideoFilename() to take in account the new file extension
64 inputVideoFile.extname = newExtname
66 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
68 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
70 // Auto destruction...
71 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
78 * Transcode the original video file to a lower resolution.
80 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
81 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
82 const extname = '.mp4'
84 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
85 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
87 const newVideoFile = new VideoFileModel({
93 const videoOutputPath = getVideoFilePath(video, newVideoFile)
94 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
96 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
98 type: 'only-audio' as 'only-audio',
100 inputPath: videoInputPath,
101 outputPath: videoTranscodedPath,
109 type: 'video' as 'video',
110 inputPath: videoInputPath,
111 outputPath: videoTranscodedPath,
117 isPortraitMode: isPortrait
120 await transcode(transcodeOptions)
122 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
125 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
126 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
127 const newExtname = '.mp4'
129 const inputVideoFile = video.getMinQualityFile()
131 const audioInputPath = getVideoFilePath(video, inputVideoFile)
132 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
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)
139 const transcodeOptions = {
140 type: 'merge-audio' as 'merge-audio',
142 inputPath: tmpPreviewPath,
143 outputPath: videoTranscodedPath,
148 audioPath: audioInputPath,
153 await transcode(transcodeOptions)
155 await remove(audioInputPath)
156 await remove(tmpPreviewPath)
158 await remove(tmpPreviewPath)
162 // Important to do this before getVideoFilename() to take in account the new file extension
163 inputVideoFile.extname = newExtname
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)
171 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
174 async function generateHlsPlaylist (options: {
175 video: MVideoWithFile
176 videoInputPath: string
177 resolution: VideoResolution
179 isPortraitMode: boolean
181 const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options
183 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
184 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
186 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
187 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
189 const transcodeOptions = {
190 type: 'hls' as 'hls',
192 inputPath: videoInputPath,
207 await transcode(transcodeOptions)
209 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
211 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
214 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
215 p2pMediaLoaderInfohashes: [],
216 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
218 type: VideoStreamingPlaylistType.HLS
219 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
220 videoStreamingPlaylist.Video = video
222 const newVideoFile = new VideoFileModel({
224 extname: extnameUtil(videoFilename),
227 videoStreamingPlaylistId: videoStreamingPlaylist.id
230 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
231 const stats = await stat(videoFilePath)
233 newVideoFile.size = stats.size
234 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
235 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
237 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
239 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
240 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
242 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
243 playlistUrl, videoStreamingPlaylist.VideoFiles
245 await videoStreamingPlaylist.save()
247 video.setHLSPlaylist(videoStreamingPlaylist)
249 await updateMasterHLSPlaylist(video)
250 await updateSha256VODSegments(video)
255 // ---------------------------------------------------------------------------
256 // Available encoders profiles
257 // ---------------------------------------------------------------------------
259 const defaultX264OptionsBuilder: EncoderOptionsBuilder = async ({ input, resolution, fps }) => {
260 if (!fps) return { outputOptions: [] }
262 let targetBitrate = getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS)
264 // Don't transcode to an higher bitrate than the original file
265 const fileBitrate = await getVideoFileBitrate(input)
266 targetBitrate = Math.min(targetBitrate, fileBitrate)
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}`
278 const defaultAACOptionsBuilder: EncoderOptionsBuilder = async ({ input }) => {
279 const parsedAudio = await getAudioStream(input)
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
284 const audioCodecName = parsedAudio.audioStream['codec_name']
286 const bitrate = getMaxAudioBitrate(audioCodecName, parsedAudio.bitrate)
288 if (bitrate !== undefined && bitrate !== -1) {
289 return { outputOptions: [ '-b:a', bitrate + 'k' ] }
292 return { outputOptions: [] }
295 const defaultLibFDKAACOptionsBuilder: EncoderOptionsBuilder = () => {
296 return { outputOptions: [ '-aq', '5' ] }
299 const availableEncoders: AvailableEncoders = {
302 default: defaultX264OptionsBuilder
305 default: defaultAACOptionsBuilder
308 default: defaultLibFDKAACOptionsBuilder
313 default: defaultX264OptionsBuilder
316 default: defaultAACOptionsBuilder
319 default: defaultLibFDKAACOptionsBuilder
324 // ---------------------------------------------------------------------------
328 optimizeOriginalVideofile,
329 transcodeNewResolution,
333 // ---------------------------------------------------------------------------
335 async 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)
340 await move(transcodingPath, outputPath, { overwrite: true })
342 videoFile.size = stats.size
344 videoFile.metadata = metadata
346 await createTorrentAndSetInfoHash(video, videoFile)
348 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
349 video.VideoFiles = await video.$get('VideoFiles')