]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-live-ending.ts
0e1bfb240fe835c787a01c8d60c2a28c8158d97d
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-live-ending.ts
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'
21
22 const lTags = loggerTagsFactory('live', 'job')
23
24 async function processVideoLiveEnding (job: Job) {
25 const payload = job.data as VideoLiveEndingPayload
26
27 logger.info('Processing video live ending for %s.', payload.videoId, { payload, ...lTags() })
28
29 function logError () {
30 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId, lTags())
31 }
32
33 const liveVideo = await VideoModel.load(payload.videoId)
34 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
35 const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId)
36
37 if (!liveVideo || !live || !liveSession) {
38 logError()
39 return
40 }
41
42 if (live.saveReplay !== true) {
43 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
44 }
45
46 if (live.permanentLive) {
47 await saveReplayToExternalVideo({ liveVideo, liveSession, publishedAt: payload.publishedAt, replayDirectory: payload.replayDirectory })
48
49 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
50 }
51
52 return replaceLiveByReplay({ liveVideo, live, liveSession, replayDirectory: payload.replayDirectory })
53 }
54
55 // ---------------------------------------------------------------------------
56
57 export {
58 processVideoLiveEnding
59 }
60
61 // ---------------------------------------------------------------------------
62
63 async function saveReplayToExternalVideo (options: {
64 liveVideo: MVideo
65 liveSession: MVideoLiveSession
66 publishedAt: string
67 replayDirectory: string
68 }) {
69 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
70
71 const video = new VideoModel({
72 name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`,
73 isLive: false,
74 state: VideoState.TO_TRANSCODE,
75 duration: 0,
76
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,
84 nsfw: liveVideo.nsfw,
85 description: liveVideo.description,
86 support: liveVideo.support,
87 privacy: liveVideo.privacy,
88 channelId: liveVideo.channelId
89 }) as MVideoWithAllFiles
90
91 video.Thumbnails = []
92 video.VideoFiles = []
93 video.VideoStreamingPlaylists = []
94
95 video.url = getLocalVideoActivityPubUrl(video)
96
97 await video.save()
98
99 liveSession.replayVideoId = video.id
100 await liveSession.save()
101
102 // If live is blacklisted, also blacklist the replay
103 const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id)
104 if (blacklist) {
105 await VideoBlacklistModel.create({
106 videoId: video.id,
107 unfederated: blacklist.unfederated,
108 reason: blacklist.reason,
109 type: blacklist.type
110 })
111 }
112
113 await assignReplayFilesToVideo({ video, replayDirectory })
114
115 await remove(replayDirectory)
116
117 for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
118 const image = await generateVideoMiniature({ video, videoFile: video.getMaxQualityFile(), type })
119 await video.addAndSaveThumbnail(image)
120 }
121
122 await moveToNextState({ video, isNewVideo: true })
123 }
124
125 async function replaceLiveByReplay (options: {
126 liveVideo: MVideo
127 liveSession: MVideoLiveSession
128 live: MVideoLive
129 replayDirectory: string
130 }) {
131 const { liveVideo, liveSession, live, replayDirectory } = options
132
133 await cleanupTMPLiveFiles(liveVideo)
134
135 await live.destroy()
136
137 liveVideo.isLive = false
138 liveVideo.waitTranscoding = true
139 liveVideo.state = VideoState.TO_TRANSCODE
140
141 await liveVideo.save()
142
143 liveSession.replayVideoId = liveVideo.id
144 await liveSession.save()
145
146 // Remove old HLS playlist video files
147 const videoWithFiles = await VideoModel.loadFull(liveVideo.id)
148
149 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
150 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
151
152 // Reset playlist
153 hlsPlaylist.VideoFiles = []
154 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
155 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
156 await hlsPlaylist.save()
157
158 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
159
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))
164 }
165
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
172 })
173 await videoWithFiles.addAndSaveThumbnail(miniature)
174 }
175
176 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
177 const preview = await generateVideoMiniature({
178 video: videoWithFiles,
179 videoFile: videoWithFiles.getMaxQualityFile(),
180 type: ThumbnailType.PREVIEW
181 })
182 await videoWithFiles.addAndSaveThumbnail(preview)
183 }
184
185 // We consider this is a new video
186 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
187 }
188
189 async function assignReplayFilesToVideo (options: {
190 video: MVideo
191 replayDirectory: string
192 }) {
193 const { video, replayDirectory } = options
194
195 let durationDone = false
196
197 const concatenatedTsFiles = await readdir(replayDirectory)
198
199 for (const concatenatedTsFile of concatenatedTsFiles) {
200 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
201
202 const probe = await ffprobePromise(concatenatedTsFilePath)
203 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
204
205 const { resolution, isPortraitMode } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
206
207 const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({
208 video,
209 concatenatedTsFilePath,
210 resolution,
211 isPortraitMode,
212 isAAC: audioStream?.codec_name === 'aac'
213 })
214
215 if (!durationDone) {
216 video.duration = await getVideoStreamDuration(outputPath)
217 await video.save()
218
219 durationDone = true
220 }
221 }
222
223 return video
224 }
225
226 async function cleanupLiveAndFederate (options: {
227 live: MVideoLive
228 video: MVideo
229 streamingPlaylistId: number
230 }) {
231 const { live, video, streamingPlaylistId } = options
232
233 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
234
235 if (streamingPlaylist) {
236 if (live.permanentLive) {
237 await cleanupPermanentLive(video, streamingPlaylist)
238 } else {
239 await cleanupUnsavedNormalLive(video, streamingPlaylist)
240 }
241 }
242
243 try {
244 const fullVideo = await VideoModel.loadFull(video.id)
245 return federateVideoIfNeeded(fullVideo, false, undefined)
246 } catch (err) {
247 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })
248 }
249 }