1 import { Job } from 'bull'
2 import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
3 import { basename, extname as extnameUtil, join } from 'path'
4 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
5 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
6 import { VideoResolution } from '../../shared/models/videos'
7 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
8 import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
9 import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
10 import { logger } from '../helpers/logger'
11 import { CONFIG } from '../initializers/config'
12 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
13 import { VideoFileModel } from '../models/video/video-file'
14 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
15 import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
16 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
17 import { availableEncoders } from './video-transcoding-profiles'
21 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
22 * Mainly called by the job queue
26 // Optimize the original video file and replace it. The resolution is not changed.
27 async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFile: MVideoFile, job?: Job) {
28 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
29 const newExtname = '.mp4'
31 const videoInputPath = getVideoFilePath(video, inputVideoFile)
32 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
34 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
38 const transcodeOptions: TranscodeOptions = {
41 inputPath: videoInputPath,
42 outputPath: videoTranscodedPath,
47 resolution: inputVideoFile.resolution,
52 // Could be very long!
53 await transcode(transcodeOptions)
56 await remove(videoInputPath)
58 // Important to do this before getVideoFilename() to take in account the new file extension
59 inputVideoFile.extname = newExtname
61 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
63 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
67 // Auto destruction...
68 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
74 // Transcode the original video file to a lower resolution.
75 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean, job: Job) {
76 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
77 const extname = '.mp4'
79 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
80 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
82 const newVideoFile = new VideoFileModel({
88 const videoOutputPath = getVideoFilePath(video, newVideoFile)
89 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
91 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
93 type: 'only-audio' as 'only-audio',
95 inputPath: videoInputPath,
96 outputPath: videoTranscodedPath,
106 type: 'video' as 'video',
107 inputPath: videoInputPath,
108 outputPath: videoTranscodedPath,
114 isPortraitMode: isPortrait,
119 await transcode(transcodeOptions)
121 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
124 // Merge an image with an audio file to create a video
125 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution, job: Job) {
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,
155 await transcode(transcodeOptions)
157 await remove(audioInputPath)
158 await remove(tmpPreviewPath)
160 await remove(tmpPreviewPath)
164 // Important to do this before getVideoFilename() to take in account the new file extension
165 inputVideoFile.extname = newExtname
167 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
168 // ffmpeg generated a new video file, so update the video duration
169 // See https://trac.ffmpeg.org/ticket/5456
170 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
173 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
176 // Concat TS segments from a live video to a fragmented mp4 HLS playlist
177 async function generateHlsPlaylistFromTS (options: {
178 video: MVideoWithFile
179 concatenatedTsFilePath: string
180 resolution: VideoResolution
181 isPortraitMode: boolean
184 return generateHlsPlaylistCommon({
185 video: options.video,
186 resolution: options.resolution,
187 isPortraitMode: options.isPortraitMode,
188 inputPath: options.concatenatedTsFilePath,
189 type: 'hls-from-ts' as 'hls-from-ts',
194 // Generate an HLS playlist from an input file, and update the master playlist
195 function generateHlsPlaylist (options: {
196 video: MVideoWithFile
197 videoInputPath: string
198 resolution: VideoResolution
200 isPortraitMode: boolean
203 return generateHlsPlaylistCommon({
204 video: options.video,
205 resolution: options.resolution,
206 copyCodecs: options.copyCodecs,
207 isPortraitMode: options.isPortraitMode,
208 inputPath: options.videoInputPath,
209 type: 'hls' as 'hls',
214 function getEnabledResolutions (type: 'vod' | 'live') {
215 const transcoding = type === 'vod'
217 : CONFIG.LIVE.TRANSCODING
219 return Object.keys(transcoding.RESOLUTIONS)
220 .filter(key => transcoding.ENABLED && transcoding.RESOLUTIONS[key] === true)
221 .map(r => parseInt(r, 10))
224 // ---------------------------------------------------------------------------
228 generateHlsPlaylistFromTS,
229 optimizeOriginalVideofile,
230 transcodeNewResolution,
232 getEnabledResolutions
235 // ---------------------------------------------------------------------------
237 async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
238 const stats = await stat(transcodingPath)
239 const fps = await getVideoFileFPS(transcodingPath)
240 const metadata = await getMetadataFromFile(transcodingPath)
242 await move(transcodingPath, outputPath, { overwrite: true })
244 videoFile.size = stats.size
246 videoFile.metadata = metadata
248 await createTorrentAndSetInfoHash(video, videoFile)
250 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
251 video.VideoFiles = await video.$get('VideoFiles')
256 async function generateHlsPlaylistCommon (options: {
257 type: 'hls' | 'hls-from-ts'
258 video: MVideoWithFile
260 resolution: VideoResolution
263 isPortraitMode: boolean
267 const { type, video, inputPath, resolution, copyCodecs, isPortraitMode, isAAC, job } = options
269 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
270 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
272 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
273 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
275 const transcodeOptions = {
297 await transcode(transcodeOptions)
299 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
301 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
304 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
305 p2pMediaLoaderInfohashes: [],
306 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
308 type: VideoStreamingPlaylistType.HLS
309 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
310 videoStreamingPlaylist.Video = video
312 const newVideoFile = new VideoFileModel({
314 extname: extnameUtil(videoFilename),
317 videoStreamingPlaylistId: videoStreamingPlaylist.id
320 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
321 const stats = await stat(videoFilePath)
323 newVideoFile.size = stats.size
324 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
325 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
327 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
329 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
330 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
332 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
333 playlistUrl, videoStreamingPlaylist.VideoFiles
335 await videoStreamingPlaylist.save()
337 video.setHLSPlaylist(videoStreamingPlaylist)
339 await updateMasterHLSPlaylist(video)
340 await updateSha256VODSegments(video)