1 import { Job } from 'bullmq'
2 import { readdir, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo } from '@server/helpers/ffmpeg'
5 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
7 import { cleanupAndDestroyPermanentLive, cleanupTMPLiveFiles, cleanupUnsavedNormalLive } from '@server/lib/live'
8 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '@server/lib/paths'
9 import { generateVideoMiniature } from '@server/lib/thumbnail'
10 import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/transcoding'
11 import { moveToNextState } from '@server/lib/video-state'
12 import { VideoModel } from '@server/models/video/video'
13 import { VideoBlacklistModel } from '@server/models/video/video-blacklist'
14 import { VideoFileModel } from '@server/models/video/video-file'
15 import { VideoLiveModel } from '@server/models/video/video-live'
16 import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
17 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
18 import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models'
19 import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models'
20 import { logger, loggerTagsFactory } from '../../../helpers/logger'
22 const lTags = loggerTagsFactory('live', 'job')
24 async function processVideoLiveEnding (job: Job) {
25 const payload = job.data as VideoLiveEndingPayload
27 logger.info('Processing video live ending for %s.', payload.videoId, { payload, ...lTags() })
29 function logError () {
30 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId, lTags())
33 const video = await VideoModel.load(payload.videoId)
34 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
35 const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId)
37 const permanentLive = live.permanentLive
39 if (!video || !live || !liveSession) {
44 liveSession.endingProcessed = true
45 await liveSession.save()
47 if (liveSession.saveReplay !== true) {
48 return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId })
52 await saveReplayToExternalVideo({
55 publishedAt: payload.publishedAt,
56 replayDirectory: payload.replayDirectory
59 return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId })
62 return replaceLiveByReplay({ video, liveSession, live, permanentLive, replayDirectory: payload.replayDirectory })
65 // ---------------------------------------------------------------------------
68 processVideoLiveEnding
71 // ---------------------------------------------------------------------------
73 async function saveReplayToExternalVideo (options: {
75 liveSession: MVideoLiveSession
77 replayDirectory: string
79 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
81 const replayVideo = new VideoModel({
82 name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`,
84 state: VideoState.TO_TRANSCODE,
87 remote: liveVideo.remote,
88 category: liveVideo.category,
89 licence: liveVideo.licence,
90 language: liveVideo.language,
91 commentsEnabled: liveVideo.commentsEnabled,
92 downloadEnabled: liveVideo.downloadEnabled,
93 waitTranscoding: true,
95 description: liveVideo.description,
96 support: liveVideo.support,
97 privacy: liveVideo.privacy,
98 channelId: liveVideo.channelId
99 }) as MVideoWithAllFiles
101 replayVideo.Thumbnails = []
102 replayVideo.VideoFiles = []
103 replayVideo.VideoStreamingPlaylists = []
105 replayVideo.url = getLocalVideoActivityPubUrl(replayVideo)
107 await replayVideo.save()
109 liveSession.replayVideoId = replayVideo.id
110 await liveSession.save()
112 // If live is blacklisted, also blacklist the replay
113 const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id)
115 await VideoBlacklistModel.create({
116 videoId: replayVideo.id,
117 unfederated: blacklist.unfederated,
118 reason: blacklist.reason,
123 await assignReplayFilesToVideo({ video: replayVideo, replayDirectory })
125 await remove(replayDirectory)
127 for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
128 const image = await generateVideoMiniature({ video: replayVideo, videoFile: replayVideo.getMaxQualityFile(), type })
129 await replayVideo.addAndSaveThumbnail(image)
132 await moveToNextState({ video: replayVideo, isNewVideo: true })
135 async function replaceLiveByReplay (options: {
137 liveSession: MVideoLiveSession
139 permanentLive: boolean
140 replayDirectory: string
142 const { video, liveSession, live, permanentLive, replayDirectory } = options
144 const videoWithFiles = await VideoModel.loadFull(video.id)
145 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
147 await cleanupTMPLiveFiles(videoWithFiles, hlsPlaylist)
151 videoWithFiles.isLive = false
152 videoWithFiles.waitTranscoding = true
153 videoWithFiles.state = VideoState.TO_TRANSCODE
155 await videoWithFiles.save()
157 liveSession.replayVideoId = videoWithFiles.id
158 await liveSession.save()
160 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
163 hlsPlaylist.VideoFiles = []
164 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
165 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
166 await hlsPlaylist.save()
168 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
170 if (permanentLive) { // Remove session replay
171 await remove(replayDirectory)
172 } else { // We won't stream again in this live, we can delete the base replay directory
173 await remove(getLiveReplayBaseDirectory(videoWithFiles))
176 // Regenerate the thumbnail & preview?
177 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
178 const miniature = await generateVideoMiniature({
179 video: videoWithFiles,
180 videoFile: videoWithFiles.getMaxQualityFile(),
181 type: ThumbnailType.MINIATURE
183 await videoWithFiles.addAndSaveThumbnail(miniature)
186 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
187 const preview = await generateVideoMiniature({
188 video: videoWithFiles,
189 videoFile: videoWithFiles.getMaxQualityFile(),
190 type: ThumbnailType.PREVIEW
192 await videoWithFiles.addAndSaveThumbnail(preview)
195 // We consider this is a new video
196 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
199 async function assignReplayFilesToVideo (options: {
201 replayDirectory: string
203 const { video, replayDirectory } = options
205 const concatenatedTsFiles = await readdir(replayDirectory)
207 for (const concatenatedTsFile of concatenatedTsFiles) {
208 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
210 const probe = await ffprobePromise(concatenatedTsFilePath)
211 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
212 const { resolution } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
214 await generateHlsPlaylistResolutionFromTS({
216 concatenatedTsFilePath,
218 isAAC: audioStream?.codec_name === 'aac'
225 async function cleanupLiveAndFederate (options: {
227 permanentLive: boolean
228 streamingPlaylistId: number
230 const { permanentLive, video, streamingPlaylistId } = options
232 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
234 if (streamingPlaylist) {
236 await cleanupAndDestroyPermanentLive(video, streamingPlaylist)
238 await cleanupUnsavedNormalLive(video, streamingPlaylist)
243 const fullVideo = await VideoModel.loadFull(video.id)
244 return federateVideoIfNeeded(fullVideo, false, undefined)
246 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })