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,
11 } from '../helpers/ffmpeg-utils'
12 import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
13 import { logger } from '../helpers/logger'
14 import { VideoResolution } from '../../shared/models/videos'
15 import { VideoFileModel } from '../models/video/video-file'
16 import { updateMasterHLSPlaylist, updateSha256Segments } from './hls'
17 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
18 import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
19 import { CONFIG } from '../initializers/config'
20 import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/typings/models'
21 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
22 import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
25 * Optimize the original video file and replace it. The resolution is not changed.
27 async function optimizeOriginalVideofile (video: MVideoWithFile, inputVideoFileArg?: MVideoFile) {
28 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
29 const newExtname = '.mp4'
31 const inputVideoFile = inputVideoFileArg || video.getMaxQualityFile()
32 const videoInputPath = getVideoFilePath(video, inputVideoFile)
33 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
35 const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath)
39 const transcodeOptions: TranscodeOptions = {
41 inputPath: videoInputPath,
42 outputPath: videoTranscodedPath,
43 resolution: inputVideoFile.resolution
46 // Could be very long!
47 await transcode(transcodeOptions)
50 await remove(videoInputPath)
52 // Important to do this before getVideoFilename() to take in account the new file extension
53 inputVideoFile.extname = newExtname
55 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
57 await onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
59 // Auto destruction...
60 video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
67 * Transcode the original video file to a lower resolution.
69 async function transcodeNewResolution (video: MVideoWithFile, resolution: VideoResolution, isPortrait: boolean) {
70 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
71 const extname = '.mp4'
73 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
74 const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile())
76 const newVideoFile = new VideoFileModel({
82 const videoOutputPath = getVideoFilePath(video, newVideoFile)
83 const videoTranscodedPath = join(transcodeDirectory, getVideoFilename(video, newVideoFile))
85 const transcodeOptions = resolution === VideoResolution.H_NOVIDEO
87 type: 'only-audio' as 'only-audio',
88 inputPath: videoInputPath,
89 outputPath: videoTranscodedPath,
93 type: 'video' as 'video',
94 inputPath: videoInputPath,
95 outputPath: videoTranscodedPath,
97 isPortraitMode: isPortrait
100 await transcode(transcodeOptions)
102 return onVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath)
105 async function mergeAudioVideofile (video: MVideoWithAllFiles, resolution: VideoResolution) {
106 const transcodeDirectory = CONFIG.STORAGE.TMP_DIR
107 const newExtname = '.mp4'
109 const inputVideoFile = video.getMinQualityFile()
111 const audioInputPath = getVideoFilePath(video, inputVideoFile)
112 const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
114 // If the user updates the video preview during transcoding
115 const previewPath = video.getPreview().getPath()
116 const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
117 await copyFile(previewPath, tmpPreviewPath)
119 const transcodeOptions = {
120 type: 'merge-audio' as 'merge-audio',
121 inputPath: tmpPreviewPath,
122 outputPath: videoTranscodedPath,
123 audioPath: audioInputPath,
128 await transcode(transcodeOptions)
130 await remove(audioInputPath)
131 await remove(tmpPreviewPath)
133 await remove(tmpPreviewPath)
137 // Important to do this before getVideoFilename() to take in account the new file extension
138 inputVideoFile.extname = newExtname
140 const videoOutputPath = getVideoFilePath(video, inputVideoFile)
141 // ffmpeg generated a new video file, so update the video duration
142 // See https://trac.ffmpeg.org/ticket/5456
143 video.duration = await getDurationFromVideoFile(videoTranscodedPath)
146 return onVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath)
149 async function generateHlsPlaylist (video: MVideoWithFile, resolution: VideoResolution, copyCodecs: boolean, isPortraitMode: boolean) {
150 const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
151 await ensureDir(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid))
153 const videoFileInput = copyCodecs
154 ? video.getWebTorrentFile(resolution)
155 : video.getMaxQualityFile()
157 const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist()
158 const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput)
160 const outputPath = join(baseHlsDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(resolution))
161 const videoFilename = generateVideoStreamingPlaylistName(video.uuid, resolution)
163 const transcodeOptions = {
164 type: 'hls' as 'hls',
165 inputPath: videoInputPath,
176 logger.debug('Will run transcode.', { transcodeOptions })
178 await transcode(transcodeOptions)
180 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
182 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
185 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid),
186 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, video.VideoFiles),
187 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
189 type: VideoStreamingPlaylistType.HLS
190 }, { returning: true }) as [ MStreamingPlaylistFilesVideo, boolean ]
191 videoStreamingPlaylist.Video = video
193 const newVideoFile = new VideoFileModel({
195 extname: extnameUtil(videoFilename),
198 videoStreamingPlaylistId: videoStreamingPlaylist.id
201 const videoFilePath = getVideoFilePath(videoStreamingPlaylist, newVideoFile)
202 const stats = await stat(videoFilePath)
204 newVideoFile.size = stats.size
205 newVideoFile.fps = await getVideoFileFPS(videoFilePath)
206 newVideoFile.metadata = await getMetadataFromFile(videoFilePath)
208 await createTorrentAndSetInfoHash(videoStreamingPlaylist, newVideoFile)
210 await VideoFileModel.customUpsert(newVideoFile, 'streaming-playlist', undefined)
211 videoStreamingPlaylist.VideoFiles = await videoStreamingPlaylist.$get('VideoFiles')
213 video.setHLSPlaylist(videoStreamingPlaylist)
215 await updateMasterHLSPlaylist(video)
216 await updateSha256Segments(video)
221 // ---------------------------------------------------------------------------
225 optimizeOriginalVideofile,
226 transcodeNewResolution,
230 // ---------------------------------------------------------------------------
232 async function onVideoFileTranscoding (video: MVideoWithFile, videoFile: MVideoFile, transcodingPath: string, outputPath: string) {
233 const stats = await stat(transcodingPath)
234 const fps = await getVideoFileFPS(transcodingPath)
235 const metadata = await getMetadataFromFile(transcodingPath)
237 await move(transcodingPath, outputPath)
239 videoFile.size = stats.size
241 videoFile.metadata = metadata
243 await createTorrentAndSetInfoHash(video, videoFile)
245 const updatedVideoFile = await videoFile.save()
247 // Add it if this is a new created file
248 if (video.VideoFiles.some(f => f.id === videoFile.id) === false) {
249 video.VideoFiles.push(updatedVideoFile)