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 { VideoResolution } from '../../shared/models/videos'
6 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
7 import { transcode, TranscodeOptions, TranscodeOptionsType } from '../helpers/ffmpeg-utils'
8 import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../helpers/ffprobe-utils'
9 import { logger } from '../helpers/logger'
10 import { CONFIG } from '../initializers/config'
11 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
12 import { VideoFileModel } from '../models/video/video-file'
13 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
14 import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
15 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
16 import { availableEncoders } from './video-transcoding-profiles'
20 * Functions that run transcoding functions, update the database, cleanup files, create torrent files...
21 * Mainly called by the job queue
25 // Optimize the original video file and replace it. The resolution is not changed.
26 async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
27 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
28 const newExtname = '.mp4'
30 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
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
50 // Could be very long!
51 await transcode(transcodeOptions)
54 await remove(videoInputPath)
56 // Important to do this before getVideoFilename() to take in account the new file extension
57 inputVideoFile.extname = newExtname
59 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
61 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
63 // Auto destruction...
64 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
70 // Transcode the original video file to a lower resolution.
71 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
72 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
73 const extname = '.mp4'
75 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
76 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
78 const newVideoFile = new VideoFileModel({
84 const videoOutputPath = getVideoFilePath(video, newVideoFile)
85 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
87 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
89 type: 'only-audio' as 'only-audio',
91 inputPath: videoInputPath,
92 outputPath: videoTranscodedPath,
100 type: 'video' as 'video',
101 inputPath: videoInputPath,
102 outputPath: videoTranscodedPath,
108 isPortraitMode: isPortrait
111 await transcode(transcodeOptions)
113 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
116 // Merge an image with an audio file to create a video
117 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
118 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
119 const newExtname = '.mp4'
121 const inputVideoFile = video.getMinQualityFile()
123 const audioInputPath = getVideoFilePath(video, inputVideoFile)
124 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
126 // If the user updates the video preview during transcoding
127 const previewPath = video.getPreview().getPath()
128 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
129 await copyFile(previewPath, tmpPreviewPath)
131 const transcodeOptions = {
132 type: 'merge-audio' as 'merge-audio',
134 inputPath: tmpPreviewPath,
135 outputPath: videoTranscodedPath,
140 audioPath: audioInputPath,
145 await transcode(transcodeOptions)
147 await remove(audioInputPath)
148 await remove(tmpPreviewPath)
150 await remove(tmpPreviewPath)
154 // Important to do this before getVideoFilename() to take in account the new file extension
155 inputVideoFile.extname = newExtname
157 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
158 // ffmpeg generated a new video file, so update the video duration
159 // See https://trac.ffmpeg.org/ticket/5456
160 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
163 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
166 // Generate an HLS playlist from an input file, and update the master playlist
167 async function generateHlsPlaylist (options: {
168 video: MVideoWithFile
169 videoInputPath: string
170 resolution: VideoResolution
172 isPortraitMode: boolean
174 const { video, videoInputPath, resolution, copyCodecs, isPortraitMode } = options
176 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
177 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
179 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
180 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
182 const transcodeOptions = {
183 type: 'hls' as 'hls',
185 inputPath: videoInputPath,
200 await transcode(transcodeOptions)
202 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
204 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
207 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
208 p2pMediaLoaderInfohashes: [],
209 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
211 type: VideoStreamingPlaylistType.HLS
212 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
213 videoStreamingPlaylist.Video = video
215 const newVideoFile = new VideoFileModel({
217 extname: extnameUtil(videoFilename),
220 videoStreamingPlaylistId: videoStreamingPlaylist.id
223 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
224 const stats = await stat(videoFilePath)
226 newVideoFile.size = stats.size
227 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
228 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
230 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
232 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
233 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
235 videoStreamingPlaylist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(
236 playlistUrl, videoStreamingPlaylist.VideoFiles
238 await videoStreamingPlaylist.save()
240 video.setHLSPlaylist(videoStreamingPlaylist)
242 await updateMasterHLSPlaylist(video)
243 await updateSha256VODSegments(video)
248 // ---------------------------------------------------------------------------
252 optimizeOriginalVideofile,
253 transcodeNewResolution,
257 // ---------------------------------------------------------------------------
259 async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
260 const stats = await stat(transcodingPath)
261 const fps = await getVideoFileFPS(transcodingPath)
262 const metadata = await getMetadataFromFile(transcodingPath)
264 await move(transcodingPath, outputPath, { overwrite: true })
266 videoFile.size = stats.size
268 videoFile.metadata = metadata
270 await createTorrentAndSetInfoHash(video, videoFile)
272 await VideoFileModel.customUpsert(videoFile, 'video', undefined)
273 video.VideoFiles = await video.$get('VideoFiles')