1 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, WEBSERVER } from '../initializers/constants'
2 import { basename, extname as extnameUtil, join } from 'path'
5 getDurationFromVideoFile,
10 } from '../helpers/ffmpeg-utils'
11 import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
12 import { logger } from '../helpers/logger'
13 import { VideoResolution } from '../../shared/models/videos'
14 import { VideoFileModel } from '../models/video/video-file'
15 import { updateMasterHLSPlaylist, updateSha256Segments } from './hls'
16 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
17 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
18 import { CONFIG } from '../initializers/config'
19 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/typings/models'
20 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
21 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
24 * 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 = {
40 inputPath: videoInputPath,
41 outputPath: videoTranscodedPath,
42 resolution: inputVideoFile.resolution
45 // Could be very long!
46 await transcode(transcodeOptions)
49 await remove(videoInputPath)
51 // Important to do this before getVideoFilename() to take in account the new file extension
52 inputVideoFile.extname = newExtname
54 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
56 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
58 // Auto destruction...
59 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
66 * Transcode the original video file to a lower resolution.
68 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
69 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
70 const extname = '.mp4'
72 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
73 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
75 const newVideoFile = new VideoFileModel({
81 const videoOutputPath = getVideoFilePath(video, newVideoFile)
82 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
84 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
86 type: 'split-audio' as 'split-audio',
87 inputPath: videoInputPath,
88 outputPath: videoTranscodedPath,
92 type: 'video' as 'video',
93 inputPath: videoInputPath,
94 outputPath: videoTranscodedPath,
96 isPortraitMode: isPortrait
99 await transcode(transcodeOptions)
101 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
105 * Extract audio into a separate audio-only mp4.
107 async function splitAudioFile (video: MVideoWithFile) {
108 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
109 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
110 const extname = '.mp4'
111 const resolution = VideoResolution.H_NOVIDEO
113 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
114 const videoInputPath = join(videosDirectory, video.getVideoFilename(video.getOriginalFile()))
116 const newVideoFile = new VideoFileModel({
122 const videoOutputPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(newVideoFile))
123 const videoTranscodedPath = join(transcodeDirectory, video.getVideoFilename(newVideoFile))
125 const transcodeOptions = {
126 type: 'split-audio' as 'split-audio',
127 inputPath: videoInputPath,
128 outputPath: videoTranscodedPath,
132 await transcode(transcodeOptions)
134 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
137 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
138 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
139 const newExtname = '.mp4'
141 const inputVideoFile = video.getMaxQualityFile()
143 const audioInputPath = getVideoFilePath(video, inputVideoFile)
144 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
146 // If the user updates the video preview during transcoding
147 const previewPath = video.getPreview().getPath()
148 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
149 await copyFile(previewPath, tmpPreviewPath)
151 const transcodeOptions = {
152 type: 'merge-audio' as 'merge-audio',
153 inputPath: tmpPreviewPath,
154 outputPath: videoTranscodedPath,
155 audioPath: audioInputPath,
160 await transcode(transcodeOptions)
162 await remove(audioInputPath)
163 await remove(tmpPreviewPath)
165 await remove(tmpPreviewPath)
169 // Important to do this before getVideoFilename() to take in account the new file extension
170 inputVideoFile.extname = newExtname
172 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
173 // ffmpeg generated a new video file, so update the video duration
174 // See https://trac.ffmpeg.org/ticket/5456
175 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
178 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
181 async function generateHlsPlaylist (video: MVideoWithFile, resolution: VideoResolution, copyCodecs: boolean, isPortraitMode: boolean) {
182 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
183 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
185 const videoFileInput = copyCodecs
186 ? video.getWebTorrentFile(resolution)
187 : video.getMaxQualityFile()
189 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
190 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
192 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
193 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
195 const transcodeOptions = {
196 type: 'hls' as 'hls',
197 inputPath: videoInputPath,
208 logger.debug('Will run transcode.', { transcodeOptions })
210 await transcode(transcodeOptions)
212 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
214 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
217 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid),
218 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, video.VideoFiles),
219 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
221 type: VideoStreamingPlaylistType.HLS
222 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
223 videoStreamingPlaylist.Video = video
225 const newVideoFile = new VideoFileModel({
227 extname: extnameUtil(videoFilename),
230 videoStreamingPlaylistId: videoStreamingPlaylist.id
233 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
234 const stats = await stat(videoFilePath)
236 newVideoFile.size = stats.size
237 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
239 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
241 const updatedVideoFile = await newVideoFile.save()
243 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles') as VideoFileModel[]
244 videoStreamingPlaylist.VideoFiles.push(updatedVideoFile)
246 video.setHLSPlaylist(videoStreamingPlaylist)
248 await updateMasterHLSPlaylist(video)
249 await updateSha256Segments(video)
254 // ---------------------------------------------------------------------------
258 optimizeOriginalVideofile,
259 transcodeNewResolution,
263 // ---------------------------------------------------------------------------
265 async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
266 const stats = await stat(transcodingPath)
267 const fps = await getVideoFileFPS(transcodingPath)
269 await move(transcodingPath, outputPath)
271 videoFile.size = stats.size
274 await createTorrentAndSetInfoHash(video, videoFile)
276 const updatedVideoFile = await videoFile.save()
278 // Add it if this is a new created file
279 if (video.VideoFiles.some(f => f.id === videoFile.id) === false) {
280 video.VideoFiles.push(updatedVideoFile)