]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/video-live-ending.ts
Update embed URL query doc
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-live-ending.ts
CommitLineData
41fb13c3 1import { Job } from 'bull'
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
26e3e98f 33 const liveVideo = 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
26e3e98f 37 if (!liveVideo || !live || !liveSession) {
68e70a74
C
38 logError()
39 return
40 }
41
b5b68755 42 if (live.saveReplay !== true) {
cdd83816 43 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
b5b68755
C
44 }
45
4ec52d04 46 if (live.permanentLive) {
26e3e98f 47 await saveReplayToExternalVideo({ liveVideo, liveSession, publishedAt: payload.publishedAt, replayDirectory: payload.replayDirectory })
4ec52d04 48
cdd83816 49 return cleanupLiveAndFederate({ live, video: liveVideo, streamingPlaylistId: payload.streamingPlaylistId })
4ec52d04
C
50 }
51
26e3e98f 52 return replaceLiveByReplay({ liveVideo, live, liveSession, replayDirectory: payload.replayDirectory })
b5b68755
C
53}
54
55// ---------------------------------------------------------------------------
56
57export {
8ebf2a5d 58 processVideoLiveEnding
b5b68755
C
59}
60
61// ---------------------------------------------------------------------------
62
26e3e98f
C
63async function saveReplayToExternalVideo (options: {
64 liveVideo: MVideo
65 liveSession: MVideoLiveSession
66 publishedAt: string
67 replayDirectory: string
68}) {
69 const { liveVideo, liveSession, publishedAt, replayDirectory } = options
70
4ec52d04
C
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,
26e3e98f 83 waitTranscoding: true,
4ec52d04
C
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
26e3e98f
C
99 liveSession.replayVideoId = video.id
100 await liveSession.save()
101
4ec52d04
C
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
26e3e98f 113 await assignReplayFilesToVideo({ video, replayDirectory })
937581b8 114
4ec52d04
C
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 }
937581b8 121
4ec52d04
C
122 await moveToNextState({ video, isNewVideo: true })
123}
937581b8 124
26e3e98f
C
125async function replaceLiveByReplay (options: {
126 liveVideo: MVideo
127 liveSession: MVideoLiveSession
128 live: MVideoLive
129 replayDirectory: string
130}) {
131 const { liveVideo, liveSession, live, replayDirectory } = options
132
92083e42 133 await cleanupTMPLiveFiles(liveVideo)
b5b68755 134
31c82cd9
C
135 await live.destroy()
136
26e3e98f
C
137 liveVideo.isLive = false
138 liveVideo.waitTranscoding = true
139 liveVideo.state = VideoState.TO_TRANSCODE
d846d99c 140
26e3e98f
C
141 await liveVideo.save()
142
143 liveSession.replayVideoId = liveVideo.id
144 await liveSession.save()
b5b68755 145
97969c4e 146 // Remove old HLS playlist video files
26e3e98f 147 const videoWithFiles = await VideoModel.loadAndPopulateAccountAndServerAndTags(liveVideo.id)
b5b68755 148
97969c4e
C
149 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
150 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
764b1a14
C
151
152 // Reset playlist
97969c4e 153 hlsPlaylist.VideoFiles = []
764b1a14
C
154 hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename()
155 hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename()
156 await hlsPlaylist.save()
97969c4e 157
26e3e98f 158 await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory })
4ec52d04 159
5333788c
C
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 }
4ec52d04
C
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 })
26e3e98f 173 await videoWithFiles.addAndSaveThumbnail(miniature)
4ec52d04
C
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 })
26e3e98f 182 await videoWithFiles.addAndSaveThumbnail(preview)
4ec52d04
C
183 }
184
26e3e98f
C
185 // We consider this is a new video
186 await moveToNextState({ video: videoWithFiles, isNewVideo: true })
4ec52d04
C
187}
188
26e3e98f
C
189async function assignReplayFilesToVideo (options: {
190 video: MVideo
191 replayDirectory: string
192}) {
193 const { video, replayDirectory } = options
194
a800dbf3 195 let durationDone = false
b5b68755 196
4ec52d04
C
197 const concatenatedTsFiles = await readdir(replayDirectory)
198
199 for (const concatenatedTsFile of concatenatedTsFiles) {
3851e732 200 const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile)
2650d6d4 201
e772bdf1
C
202 const probe = await ffprobePromise(concatenatedTsFilePath)
203 const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe)
204
c729caf6 205 const { resolution, isPortraitMode } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe)
2650d6d4 206
0305db28 207 const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({
4ec52d04 208 video,
3851e732 209 concatenatedTsFilePath,
679c12e6 210 resolution,
e772bdf1
C
211 isPortraitMode,
212 isAAC: audioStream?.codec_name === 'aac'
b5b68755 213 })
b5b68755 214
4a54a939 215 if (!durationDone) {
4ec52d04
C
216 video.duration = await getVideoStreamDuration(outputPath)
217 await video.save()
4a54a939
C
218
219 durationDone = true
2650d6d4 220 }
97969c4e 221 }
d846d99c 222
4ec52d04
C
223 return video
224}
053aed43 225
26e3e98f 226async function cleanupLiveAndFederate (options: {
5333788c
C
227 live: MVideoLive
228 video: MVideo
cdd83816 229 streamingPlaylistId: number
26e3e98f 230}) {
cdd83816 231 const { live, video, streamingPlaylistId } = options
bb4ba6d9 232
cdd83816 233 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
a5cf76af 234
cdd83816
C
235 if (streamingPlaylist) {
236 if (live.permanentLive) {
237 await cleanupPermanentLive(video, streamingPlaylist)
238 } else {
53023be3 239 await cleanupUnsavedNormalLive(video, streamingPlaylist)
cdd83816 240 }
a5cf76af 241 }
5333788c 242
c8fdfab0
C
243 try {
244 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
245 return federateVideoIfNeeded(fullVideo, false, undefined)
246 } catch (err) {
247 logger.warn('Cannot federate live after cleanup', { videoId: video.id, err })
248 }
a5cf76af 249}