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