1 import * as Bull from 'bull'
2 import { move, readdir, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { hlsPlaylistToFragmentedMP4 } from '@server/helpers/ffmpeg-utils'
5 import { getDurationFromVideoFile, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
6 import { generateVideoMiniature } from '@server/lib/thumbnail'
7 import { publishAndFederateIfNeeded } from '@server/lib/video'
8 import { getHLSDirectory } from '@server/lib/video-paths'
9 import { generateHlsPlaylist } from '@server/lib/video-transcoding'
10 import { VideoModel } from '@server/models/video/video'
11 import { VideoFileModel } from '@server/models/video/video-file'
12 import { VideoLiveModel } from '@server/models/video/video-live'
13 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14 import { MStreamingPlaylist, MVideo, MVideoLive } from '@server/types/models'
15 import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models'
16 import { logger } from '../../../helpers/logger'
17 import { VIDEO_LIVE } from '@server/initializers/constants'
19 async function processVideoLiveEnding (job: Bull.Job) {
20 const payload = job.data as VideoLiveEndingPayload
22 function logError () {
23 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId)
26 const video = await VideoModel.load(payload.videoId)
27 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
29 if (!video || !live) {
34 const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
35 if (!streamingPlaylist) {
40 if (live.saveReplay !== true) {
41 return cleanupLive(video, streamingPlaylist)
44 return saveLive(video, live)
47 // ---------------------------------------------------------------------------
50 processVideoLiveEnding
53 // ---------------------------------------------------------------------------
55 async function saveLive (video: MVideo, live: MVideoLive) {
56 const hlsDirectory = getHLSDirectory(video, false)
57 const replayDirectory = join(hlsDirectory, VIDEO_LIVE.REPLAY_DIRECTORY)
59 const rootFiles = await readdir(hlsDirectory)
61 const playlistFiles: string[] = []
63 for (const file of rootFiles) {
64 if (file.endsWith('.m3u8') !== true) continue
66 await move(join(hlsDirectory, file), join(replayDirectory, file))
68 if (file !== 'master.m3u8') {
69 playlistFiles.push(file)
73 const replayFiles = await readdir(replayDirectory)
75 const resolutions: number[] = []
78 for (const playlistFile of playlistFiles) {
79 const playlistPath = join(replayDirectory, playlistFile)
80 const { videoFileResolution } = await getVideoFileResolution(playlistPath)
82 // Put the final mp4 in the hls directory, and not in the replay directory
83 const mp4TmpPath = buildMP4TmpPath(hlsDirectory, videoFileResolution)
85 // Playlist name is for example 3.m3u8
86 // Segments names are 3-0.ts 3-1.ts etc
87 const shouldStartWith = playlistFile.replace(/\.m3u8$/, '') + '-'
89 const segmentFiles = replayFiles.filter(f => f.startsWith(shouldStartWith) && f.endsWith('.ts'))
90 await hlsPlaylistToFragmentedMP4(replayDirectory, segmentFiles, mp4TmpPath)
93 duration = await getDurationFromVideoFile(mp4TmpPath)
96 resolutions.push(videoFileResolution)
99 await cleanupLiveFiles(hlsDirectory)
106 video.state = VideoState.TO_TRANSCODE
107 video.duration = duration
111 // Remove old HLS playlist video files
112 const videoWithFiles = await VideoModel.loadWithFiles(video.id)
114 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
115 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
116 hlsPlaylist.VideoFiles = []
118 for (const resolution of resolutions) {
119 const videoInputPath = buildMP4TmpPath(hlsDirectory, resolution)
120 const { isPortraitMode } = await getVideoFileResolution(videoInputPath)
122 await generateHlsPlaylist({
123 video: videoWithFiles,
125 resolution: resolution,
130 await remove(videoInputPath)
133 // Regenerate the thumbnail & preview?
134 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
135 await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.MINIATURE)
138 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
139 await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.PREVIEW)
142 await publishAndFederateIfNeeded(video, true)
145 async function cleanupLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) {
146 const hlsDirectory = getHLSDirectory(video)
148 await remove(hlsDirectory)
150 streamingPlaylist.destroy()
151 .catch(err => logger.error('Cannot remove live streaming playlist.', { err }))
154 async function cleanupLiveFiles (hlsDirectory: string) {
155 const files = await readdir(hlsDirectory)
157 for (const filename of files) {
159 filename.endsWith('.ts') ||
160 filename.endsWith('.m3u8') ||
161 filename.endsWith('.mpd') ||
162 filename.endsWith('.m4s') ||
163 filename.endsWith('.tmp') ||
164 filename === VIDEO_LIVE.REPLAY_DIRECTORY
166 const p = join(hlsDirectory, filename)
169 .catch(err => logger.error('Cannot remove %s.', p, { err }))
174 function buildMP4TmpPath (basePath: string, resolution: number) {
175 return join(basePath, resolution + '-tmp.mp4')