]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-live-ending.ts
Use worker thread to send HTTP requests
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-live-ending.ts
CommitLineData
5a921e7b 1import { Job } from 'bullmq'
5333788c 2import { readdir, remove } from 'fs-extra'
a5cf76af 3import { join } from 'path'
4ec52d04
C
4import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamDuration } from '@server/helpers/ffmpeg'
5import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
92083e42
C
7import { cleanupPermanentLive, cleanupTMPLiveFiles, cleanupUnsavedNormalLive } from '@server/lib/live'
8import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '@server/lib/paths'
daf6e480 9import { generateVideoMiniature } from '@server/lib/thumbnail'
c729caf6 10import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/transcoding'
0305db28 11import { moveToNextState } from '@server/lib/video-state'
a5cf76af 12import { VideoModel } from '@server/models/video/video'
26e3e98f 13import { VideoBlacklistModel } from '@server/models/video/video-blacklist'
68e70a74 14import { VideoFileModel } from '@server/models/video/video-file'
b5b68755 15import { VideoLiveModel } from '@server/models/video/video-live'
26e3e98f 16import { VideoLiveSessionModel } from '@server/models/video/video-live-session'
a5cf76af 17import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
26e3e98f 18import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models'
053aed43 19import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models'
53023be3
C
20import { logger, loggerTagsFactory } from '../../../helpers/logger'
21
22const lTags = loggerTagsFactory('live', 'job')
a5cf76af 23
41fb13c3 24async function processVideoLiveEnding (job: Job) {
a5cf76af
C
25 const payload = job.data as VideoLiveEndingPayload
26
53023be3 27 logger.info('Processing video live ending for %s.', payload.videoId, { payload, ...lTags() })
4ec52d04 28
68e70a74 29 function logError () {
53023be3 30 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId, lTags())
68e70a74
C
31 }
32
c8fa571f 33 const video = await VideoModel.load(payload.videoId)
b5b68755 34 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
26e3e98f 35 const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId)
b5b68755 36
c8fa571f
C
37 const permanentLive = live.permanentLive
38
39 if (!video || !live || !liveSession) {
68e70a74
C
40 logError()
41 return
42 }
43
c8fa571f
C
44 liveSession.endingProcessed = true
45 await liveSession.save()
46
47 if (liveSession.saveReplay !== true) {
48 return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId })
b5b68755
C
49 }
50
c8fa571f
C
51 if (permanentLive) {
52 await saveReplayToExternalVideo({
53 liveVideo: video,
54 liveSession,
55 publishedAt: payload.publishedAt,
56 replayDirectory: payload.replayDirectory
57 })
4ec52d04 58
c8fa571f 59 return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId })
4ec52d04
C
60 }
61
c8fa571f 62 return replaceLiveByReplay({ video, liveSession, live, permanentLive, replayDirectory: payload.replayDirectory })
b5b68755
C
63}
64
65// ---------------------------------------------------------------------------
66
67export {
8ebf2a5d 68 processVideoLiveEnding
b5b68755
C
69}
70
71// ---------------------------------------------------------------------------
72
26e3e98f
C
73async function saveReplayToExternalVideo (options: {
74 liveVideo: MVideo
75 liveSession: MVideoLiveSession
76 publishedAt: string
77 replayDirectory: string
78}) {
79 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
80
c8fa571f 81 const replayVideo = new VideoModel({
4ec52d04
C
82 name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`,
83 isLive: false,
84 state: VideoState.TO_TRANSCODE,
85 duration: 0,
86
87 remote: liveVideo.remote,
88 category: liveVideo.category,
89 licence: liveVideo.licence,
90 language: liveVideo.language,
91 commentsEnabled: liveVideo.commentsEnabled,
92 downloadEnabled: liveVideo.downloadEnabled,
26e3e98f 93 waitTranscoding: true,
4ec52d04
C
94 nsfw: liveVideo.nsfw,
95 description: liveVideo.description,
96 support: liveVideo.support,
97 privacy: liveVideo.privacy,
98 channelId: liveVideo.channelId
99 }) as MVideoWithAllFiles
100
c8fa571f
C
101 replayVideo.Thumbnails = []
102 replayVideo.VideoFiles = []
103 replayVideo.VideoStreamingPlaylists = []
4ec52d04 104
c8fa571f 105 replayVideo.url = getLocalVideoActivityPubUrl(replayVideo)
4ec52d04 106
c8fa571f 107 await replayVideo.save()
4ec52d04 108
c8fa571f 109 liveSession.replayVideoId = replayVideo.id
26e3e98f
C
110 await liveSession.save()
111
4ec52d04
C
112 // If live is blacklisted, also blacklist the replay
113 const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id)
114 if (blacklist) {
115 await VideoBlacklistModel.create({
c8fa571f 116 videoId: replayVideo.id,
4ec52d04
C
117 unfederated: blacklist.unfederated,
118 reason: blacklist.reason,
119 type: blacklist.type
120 })
121 }
122
c8fa571f 123 await assignReplayFilesToVideo({ video: replayVideo, replayDirectory })
937581b8 124
4ec52d04
C
125 await remove(replayDirectory)
126
127 for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
c8fa571f
C
128 const image = await generateVideoMiniature({ video: replayVideo, videoFile: replayVideo.getMaxQualityFile(), type })
129 await replayVideo.addAndSaveThumbnail(image)
4ec52d04 130 }
937581b8 131
c8fa571f 132 await moveToNextState({ video: replayVideo, isNewVideo: true })
4ec52d04 133}
937581b8 134
26e3e98f 135async function replaceLiveByReplay (options: {
c8fa571f 136 video: MVideo
26e3e98f
C
137 liveSession: MVideoLiveSession
138 live: MVideoLive
c8fa571f 139 permanentLive: boolean
26e3e98f
C
140 replayDirectory: string
141}) {
c8fa571f 142 const { video, liveSession, live, permanentLive, replayDirectory } = options
26e3e98f 143
c8fa571f 144 await cleanupTMPLiveFiles(video)
b5b68755 145
31c82cd9
C
146 await live.destroy()
147
c8fa571f
C
148 video.isLive = false
149 video.waitTranscoding = true
150 video.state = VideoState.TO_TRANSCODE
d846d99c 151
c8fa571f 152 await video.save()
26e3e98f 153
c8fa571f 154 liveSession.replayVideoId = video.id
26e3e98f 155 await liveSession.save()
b5b68755 156
97969c4e 157 // Remove old HLS playlist video files
c8fa571f 158 const videoWithFiles = await VideoModel.loadFull(video.id)
b5b68755 159
97969c4e
C
160 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
161 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
764b1a14
C
162
163 // Reset playlist
97969c4e 164 hlsPlaylist.VideoFiles = []
764b1a14
C
165 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
166 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
167 await hlsPlaylist.save()
97969c4e 168
26e3e98f 169 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
4ec52d04 170
c8fa571f 171 if (permanentLive) { // Remove session replay
5333788c
C
172 await remove(replayDirectory)
173 } else { // We won't stream again in this live, we can delete the base replay directory
174 await remove(getLiveReplayBaseDirectory(videoWithFiles))
175 }
4ec52d04
C
176
177 // Regenerate the thumbnail & preview?
178 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
179 const miniature = await generateVideoMiniature({
180 video: videoWithFiles,
181 videoFile: videoWithFiles.getMaxQualityFile(),
182 type: ThumbnailType.MINIATURE
183 })
26e3e98f 184 await videoWithFiles.addAndSaveThumbnail(miniature)
4ec52d04
C
185 }
186
187 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
188 const preview = await generateVideoMiniature({
189 video: videoWithFiles,
190 videoFile: videoWithFiles.getMaxQualityFile(),
191 type: ThumbnailType.PREVIEW
192 })
26e3e98f 193 await videoWithFiles.addAndSaveThumbnail(preview)
4ec52d04
C
194 }
195
26e3e98f
C
196 // We consider this is a new video
197 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
4ec52d04
C
198}
199
26e3e98f
C
200async function assignReplayFilesToVideo (options: {
201 video: MVideo
202 replayDirectory: string
203}) {
204 const { video, replayDirectory } = options
205
a800dbf3 206 let durationDone = false
b5b68755 207
4ec52d04
C
208 const concatenatedTsFiles = await readdir(replayDirectory)
209
210 for (const concatenatedTsFile of concatenatedTsFiles) {
3851e732 211 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
2650d6d4 212
e772bdf1
C
213 const probe = await ffprobePromise(concatenatedTsFilePath)
214 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
215
84cae54e 216 const { resolution } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
2650d6d4 217
0305db28 218 const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({
4ec52d04 219 video,
3851e732 220 concatenatedTsFilePath,
679c12e6 221 resolution,
e772bdf1 222 isAAC: audioStream?.codec_name === 'aac'
b5b68755 223 })
b5b68755 224
4a54a939 225 if (!durationDone) {
4ec52d04
C
226 video.duration = await getVideoStreamDuration(outputPath)
227 await video.save()
4a54a939
C
228
229 durationDone = true
2650d6d4 230 }
97969c4e 231 }
d846d99c 232
4ec52d04
C
233 return video
234}
053aed43 235
26e3e98f 236async function cleanupLiveAndFederate (options: {
5333788c 237 video: MVideo
c8fa571f 238 permanentLive: boolean
cdd83816 239 streamingPlaylistId: number
26e3e98f 240}) {
c8fa571f 241 const { permanentLive, video, streamingPlaylistId } = options
bb4ba6d9 242
cdd83816 243 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
a5cf76af 244
cdd83816 245 if (streamingPlaylist) {
c8fa571f 246 if (permanentLive) {
cdd83816
C
247 await cleanupPermanentLive(video, streamingPlaylist)
248 } else {
53023be3 249 await cleanupUnsavedNormalLive(video, streamingPlaylist)
cdd83816 250 }
a5cf76af 251 }
5333788c 252
c8fdfab0 253 try {
4fae2b1f 254 const fullVideo = await VideoModel.loadFull(video.id)
c8fdfab0
C
255 return federateVideoIfNeeded(fullVideo, false, undefined)
256 } catch (err) {
257 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })
258 }
a5cf76af 259}