1 import { Job } from 'bull'
2 import { readdir, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamDuration } from '@server/helpers/ffmpeg'
5 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
7 import { cleanupNormalLive, cleanupPermanentLive, cleanupTMPLiveFiles, LiveSegmentShaStore } from '@server/lib/live'
9 generateHLSMasterPlaylistFilename,
10 generateHlsSha256SegmentsFilename,
12 getLiveReplayBaseDirectory
13 } from '@server/lib/paths'
14 import { generateVideoMiniature } from '@server/lib/thumbnail'
15 import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/transcoding'
16 import { moveToNextState } from '@server/lib/video-state'
17 import { VideoModel } from '@server/models/video/video'
18 import { VideoBlacklistModel } from '@server/models/video/video-blacklist'
19 import { VideoFileModel } from '@server/models/video/video-file'
20 import { VideoLiveModel } from '@server/models/video/video-live'
21 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
22 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
23 import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models'
24 import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models'
25 import { logger } from '../../../helpers/logger'
27 async function processVideoLiveEnding (job: Job) {
28 const payload = job.data as VideoLiveEndingPayload
30 logger.info('Processing video live ending for %s.', payload.videoId, { payload })
32 function logError () {
33 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId)
36 const liveVideo = await VideoModel.load(payload.videoId)
37 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
38 const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId)
40 if (!liveVideo || !live || !liveSession) {
45 LiveSegmentShaStore.Instance.cleanupShaSegments(liveVideo.uuid)
47 if (live.saveReplay !== true) {
48 return cleanupLiveAndFederate({ live, video: liveVideo })
51 if (live.permanentLive) {
52 await saveReplayToExternalVideo({ liveVideo, liveSession, publishedAt: payload.publishedAt, replayDirectory: payload.replayDirectory })
54 return cleanupLiveAndFederate({ live, video: liveVideo })
57 return replaceLiveByReplay({ liveVideo, live, liveSession, replayDirectory: payload.replayDirectory })
60 // ---------------------------------------------------------------------------
63 processVideoLiveEnding
66 // ---------------------------------------------------------------------------
68 async function saveReplayToExternalVideo (options: {
70 liveSession: MVideoLiveSession
72 replayDirectory: string
74 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
76 await cleanupTMPLiveFiles(getLiveDirectory(liveVideo))
78 const video = new VideoModel({
79 name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`,
81 state: VideoState.TO_TRANSCODE,
84 remote: liveVideo.remote,
85 category: liveVideo.category,
86 licence: liveVideo.licence,
87 language: liveVideo.language,
88 commentsEnabled: liveVideo.commentsEnabled,
89 downloadEnabled: liveVideo.downloadEnabled,
90 waitTranscoding: true,
92 description: liveVideo.description,
93 support: liveVideo.support,
94 privacy: liveVideo.privacy,
95 channelId: liveVideo.channelId
96 }) as MVideoWithAllFiles
100 video.VideoStreamingPlaylists = []
102 video.url = getLocalVideoActivityPubUrl(video)
106 liveSession.replayVideoId = video.id
107 await liveSession.save()
109 // If live is blacklisted, also blacklist the replay
110 const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id)
112 await VideoBlacklistModel.create({
114 unfederated: blacklist.unfederated,
115 reason: blacklist.reason,
120 await assignReplayFilesToVideo({ video, replayDirectory })
122 await remove(replayDirectory)
124 for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
125 const image = await generateVideoMiniature({ video, videoFile: video.getMaxQualityFile(), type })
126 await video.addAndSaveThumbnail(image)
129 await moveToNextState({ video, isNewVideo: true })
132 async function replaceLiveByReplay (options: {
134 liveSession: MVideoLiveSession
136 replayDirectory: string
138 const { liveVideo, liveSession, live, replayDirectory } = options
140 await cleanupTMPLiveFiles(getLiveDirectory(liveVideo))
144 liveVideo.isLive = false
145 liveVideo.waitTranscoding = true
146 liveVideo.state = VideoState.TO_TRANSCODE
148 await liveVideo.save()
150 liveSession.replayVideoId = liveVideo.id
151 await liveSession.save()
153 // Remove old HLS playlist video files
154 const videoWithFiles = await VideoModel.loadAndPopulateAccountAndServerAndTags(liveVideo.id)
156 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
157 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
160 hlsPlaylist.VideoFiles = []
161 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
162 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
163 await hlsPlaylist.save()
165 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
167 if (live.permanentLive) { // Remove session replay
168 await remove(replayDirectory)
169 } else { // We won't stream again in this live, we can delete the base replay directory
170 await remove(getLiveReplayBaseDirectory(videoWithFiles))
173 // Regenerate the thumbnail & preview?
174 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
175 const miniature = await generateVideoMiniature({
176 video: videoWithFiles,
177 videoFile: videoWithFiles.getMaxQualityFile(),
178 type: ThumbnailType.MINIATURE
180 await videoWithFiles.addAndSaveThumbnail(miniature)
183 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
184 const preview = await generateVideoMiniature({
185 video: videoWithFiles,
186 videoFile: videoWithFiles.getMaxQualityFile(),
187 type: ThumbnailType.PREVIEW
189 await videoWithFiles.addAndSaveThumbnail(preview)
192 // We consider this is a new video
193 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
196 async function assignReplayFilesToVideo (options: {
198 replayDirectory: string
200 const { video, replayDirectory } = options
202 let durationDone = false
204 const concatenatedTsFiles = await readdir(replayDirectory)
206 for (const concatenatedTsFile of concatenatedTsFiles) {
207 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
209 const probe = await ffprobePromise(concatenatedTsFilePath)
210 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
212 const { resolution, isPortraitMode } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
214 const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({
216 concatenatedTsFilePath,
219 isAAC: audioStream?.codec_name === 'aac'
223 video.duration = await getVideoStreamDuration(outputPath)
233 async function cleanupLiveAndFederate (options: {
237 const { live, video } = options
239 const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
241 if (live.permanentLive) {
242 await cleanupPermanentLive(video, streamingPlaylist)
244 await cleanupNormalLive(video, streamingPlaylist)
248 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
249 return federateVideoIfNeeded(fullVideo, false, undefined)
251 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })