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 { cleanupPermanentLive, 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 liveVideo = await VideoModel.load(payload.videoId)
34 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
35 const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId)
37 if (!liveVideo || !live || !liveSession) {
42 if (live.saveReplay !== true) {
43 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
46 if (live.permanentLive) {
47 await saveReplayToExternalVideo({ liveVideo, liveSession, publishedAt: payload.publishedAt, replayDirectory: payload.replayDirectory })
49 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
52 return replaceLiveByReplay({ liveVideo, live, liveSession, replayDirectory: payload.replayDirectory })
55 // ---------------------------------------------------------------------------
58 processVideoLiveEnding
61 // ---------------------------------------------------------------------------
63 async function saveReplayToExternalVideo (options: {
65 liveSession: MVideoLiveSession
67 replayDirectory: string
69 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
71 const video = new VideoModel({
72 name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`,
74 state: VideoState.TO_TRANSCODE,
77 remote: liveVideo.remote,
78 category: liveVideo.category,
79 licence: liveVideo.licence,
80 language: liveVideo.language,
81 commentsEnabled: liveVideo.commentsEnabled,
82 downloadEnabled: liveVideo.downloadEnabled,
83 waitTranscoding: true,
85 description: liveVideo.description,
86 support: liveVideo.support,
87 privacy: liveVideo.privacy,
88 channelId: liveVideo.channelId
89 }) as MVideoWithAllFiles
93 video.VideoStreamingPlaylists = []
95 video.url = getLocalVideoActivityPubUrl(video)
99 liveSession.replayVideoId = video.id
100 await liveSession.save()
102 // If live is blacklisted, also blacklist the replay
103 const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id)
105 await VideoBlacklistModel.create({
107 unfederated: blacklist.unfederated,
108 reason: blacklist.reason,
113 await assignReplayFilesToVideo({ video, replayDirectory })
115 await remove(replayDirectory)
117 for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
118 const image = await generateVideoMiniature({ video, videoFile: video.getMaxQualityFile(), type })
119 await video.addAndSaveThumbnail(image)
122 await moveToNextState({ video, isNewVideo: true })
125 async function replaceLiveByReplay (options: {
127 liveSession: MVideoLiveSession
129 replayDirectory: string
131 const { liveVideo, liveSession, live, replayDirectory } = options
133 await cleanupTMPLiveFiles(liveVideo)
137 liveVideo.isLive = false
138 liveVideo.waitTranscoding = true
139 liveVideo.state = VideoState.TO_TRANSCODE
141 await liveVideo.save()
143 liveSession.replayVideoId = liveVideo.id
144 await liveSession.save()
146 // Remove old HLS playlist video files
147 const videoWithFiles = await VideoModel.loadAndPopulateAccountAndServerAndTags(liveVideo.id)
149 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
150 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
153 hlsPlaylist.VideoFiles = []
154 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
155 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
156 await hlsPlaylist.save()
158 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
160 if (live.permanentLive) { // Remove session replay
161 await remove(replayDirectory)
162 } else { // We won't stream again in this live, we can delete the base replay directory
163 await remove(getLiveReplayBaseDirectory(videoWithFiles))
166 // Regenerate the thumbnail & preview?
167 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
168 const miniature = await generateVideoMiniature({
169 video: videoWithFiles,
170 videoFile: videoWithFiles.getMaxQualityFile(),
171 type: ThumbnailType.MINIATURE
173 await videoWithFiles.addAndSaveThumbnail(miniature)
176 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
177 const preview = await generateVideoMiniature({
178 video: videoWithFiles,
179 videoFile: videoWithFiles.getMaxQualityFile(),
180 type: ThumbnailType.PREVIEW
182 await videoWithFiles.addAndSaveThumbnail(preview)
185 // We consider this is a new video
186 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
189 async function assignReplayFilesToVideo (options: {
191 replayDirectory: string
193 const { video, replayDirectory } = options
195 let durationDone = false
197 const concatenatedTsFiles = await readdir(replayDirectory)
199 for (const concatenatedTsFile of concatenatedTsFiles) {
200 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
202 const probe = await ffprobePromise(concatenatedTsFilePath)
203 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
205 const { resolution, isPortraitMode } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
207 const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({
209 concatenatedTsFilePath,
212 isAAC: audioStream?.codec_name === 'aac'
216 video.duration = await getVideoStreamDuration(outputPath)
226 async function cleanupLiveAndFederate (options: {
229 streamingPlaylistId: number
231 const { live, video, streamingPlaylistId } = options
233 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
235 if (streamingPlaylist) {
236 if (live.permanentLive) {
237 await cleanupPermanentLive(video, streamingPlaylist)
239 await cleanupUnsavedNormalLive(video, streamingPlaylist)
244 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
245 return federateVideoIfNeeded(fullVideo, false, undefined)
247 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })