]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/video-live-ending.ts
Fix high CPU with long live when save replay is true
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / video-live-ending.ts
1 import * as Bull from 'bull'
2 import { move, readdir, remove } from 'fs-extra'
3 import { join } from 'path'
4 import { hlsPlaylistToFragmentedMP4 } from '@server/helpers/ffmpeg-utils'
5 import { getDurationFromVideoFile, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
6 import { generateVideoMiniature } from '@server/lib/thumbnail'
7 import { publishAndFederateIfNeeded } from '@server/lib/video'
8 import { getHLSDirectory } from '@server/lib/video-paths'
9 import { generateHlsPlaylist } from '@server/lib/video-transcoding'
10 import { VideoModel } from '@server/models/video/video'
11 import { VideoFileModel } from '@server/models/video/video-file'
12 import { VideoLiveModel } from '@server/models/video/video-live'
13 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14 import { MStreamingPlaylist, MVideo, MVideoLive } from '@server/types/models'
15 import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models'
16 import { logger } from '../../../helpers/logger'
17 import { VIDEO_LIVE } from '@server/initializers/constants'
18
19 async function processVideoLiveEnding (job: Bull.Job) {
20 const payload = job.data as VideoLiveEndingPayload
21
22 function logError () {
23 logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId)
24 }
25
26 const video = await VideoModel.load(payload.videoId)
27 const live = await VideoLiveModel.loadByVideoId(payload.videoId)
28
29 if (!video || !live) {
30 logError()
31 return
32 }
33
34 const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
35 if (!streamingPlaylist) {
36 logError()
37 return
38 }
39
40 if (live.saveReplay !== true) {
41 return cleanupLive(video, streamingPlaylist)
42 }
43
44 return saveLive(video, live)
45 }
46
47 // ---------------------------------------------------------------------------
48
49 export {
50 processVideoLiveEnding
51 }
52
53 // ---------------------------------------------------------------------------
54
55 async function saveLive (video: MVideo, live: MVideoLive) {
56 const hlsDirectory = getHLSDirectory(video, false)
57 const replayDirectory = join(hlsDirectory, VIDEO_LIVE.REPLAY_DIRECTORY)
58
59 const rootFiles = await readdir(hlsDirectory)
60
61 const playlistFiles: string[] = []
62
63 for (const file of rootFiles) {
64 if (file.endsWith('.m3u8') !== true) continue
65
66 await move(join(hlsDirectory, file), join(replayDirectory, file))
67
68 if (file !== 'master.m3u8') {
69 playlistFiles.push(file)
70 }
71 }
72
73 const replayFiles = await readdir(replayDirectory)
74
75 const resolutions: number[] = []
76 let duration: number
77
78 for (const playlistFile of playlistFiles) {
79 const playlistPath = join(replayDirectory, playlistFile)
80 const { videoFileResolution } = await getVideoFileResolution(playlistPath)
81
82 // Put the final mp4 in the hls directory, and not in the replay directory
83 const mp4TmpPath = buildMP4TmpPath(hlsDirectory, videoFileResolution)
84
85 // Playlist name is for example 3.m3u8
86 // Segments names are 3-0.ts 3-1.ts etc
87 const shouldStartWith = playlistFile.replace(/\.m3u8$/, '') + '-'
88
89 const segmentFiles = replayFiles.filter(f => f.startsWith(shouldStartWith) && f.endsWith('.ts'))
90 await hlsPlaylistToFragmentedMP4(replayDirectory, segmentFiles, mp4TmpPath)
91
92 if (!duration) {
93 duration = await getDurationFromVideoFile(mp4TmpPath)
94 }
95
96 resolutions.push(videoFileResolution)
97 }
98
99 await cleanupLiveFiles(hlsDirectory)
100
101 await live.destroy()
102
103 video.isLive = false
104 // Reinit views
105 video.views = 0
106 video.state = VideoState.TO_TRANSCODE
107 video.duration = duration
108
109 await video.save()
110
111 // Remove old HLS playlist video files
112 const videoWithFiles = await VideoModel.loadWithFiles(video.id)
113
114 const hlsPlaylist = videoWithFiles.getHLSPlaylist()
115 await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id)
116 hlsPlaylist.VideoFiles = []
117
118 for (const resolution of resolutions) {
119 const videoInputPath = buildMP4TmpPath(hlsDirectory, resolution)
120 const { isPortraitMode } = await getVideoFileResolution(videoInputPath)
121
122 await generateHlsPlaylist({
123 video: videoWithFiles,
124 videoInputPath,
125 resolution: resolution,
126 copyCodecs: true,
127 isPortraitMode
128 })
129
130 await remove(videoInputPath)
131 }
132
133 // Regenerate the thumbnail & preview?
134 if (videoWithFiles.getMiniature().automaticallyGenerated === true) {
135 await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.MINIATURE)
136 }
137
138 if (videoWithFiles.getPreview().automaticallyGenerated === true) {
139 await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.PREVIEW)
140 }
141
142 await publishAndFederateIfNeeded(video, true)
143 }
144
145 async function cleanupLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) {
146 const hlsDirectory = getHLSDirectory(video)
147
148 await remove(hlsDirectory)
149
150 streamingPlaylist.destroy()
151 .catch(err => logger.error('Cannot remove live streaming playlist.', { err }))
152 }
153
154 async function cleanupLiveFiles (hlsDirectory: string) {
155 const files = await readdir(hlsDirectory)
156
157 for (const filename of files) {
158 if (
159 filename.endsWith('.ts') ||
160 filename.endsWith('.m3u8') ||
161 filename.endsWith('.mpd') ||
162 filename.endsWith('.m4s') ||
163 filename.endsWith('.tmp') ||
164 filename === VIDEO_LIVE.REPLAY_DIRECTORY
165 ) {
166 const p = join(hlsDirectory, filename)
167
168 remove(p)
169 .catch(err => logger.error('Cannot remove %s.', p, { err }))
170 }
171 }
172 }
173
174 function buildMP4TmpPath (basePath: string, resolution: number) {
175 return join(basePath, resolution + '-tmp.mp4')
176 }