]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/live/live-manager.ts
Move apicache in peertube
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-manager.ts
CommitLineData
8ebf2a5d
C
1
2import { createServer, Server } from 'net'
3import { isTestInstance } from '@server/helpers/core-utils'
4import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils'
5import { logger, loggerTagsFactory } from '@server/helpers/logger'
6import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
7import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants'
8import { UserModel } from '@server/models/user/user'
9import { VideoModel } from '@server/models/video/video'
10import { VideoLiveModel } from '@server/models/video/video-live'
11import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
12import { MStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
13import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
14import { federateVideoIfNeeded } from '../activitypub/videos'
15import { JobQueue } from '../job-queue'
16import { PeerTubeSocket } from '../peertube-socket'
17import { LiveQuotaStore } from './live-quota-store'
18import { LiveSegmentShaStore } from './live-segment-sha-store'
19import { cleanupLive } from './live-utils'
20import { MuxingSession } from './shared'
21
22const NodeRtmpSession = require('node-media-server/node_rtmp_session')
23const context = require('node-media-server/node_core_ctx')
24const nodeMediaServerLogger = require('node-media-server/node_core_logger')
25
26// Disable node media server logs
27nodeMediaServerLogger.setLogType(0)
28
29const config = {
30 rtmp: {
31 port: CONFIG.LIVE.RTMP.PORT,
32 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
33 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
34 ping: VIDEO_LIVE.RTMP.PING,
35 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
36 },
37 transcoding: {
38 ffmpeg: 'ffmpeg'
39 }
40}
41
42const lTags = loggerTagsFactory('live')
43
44class LiveManager {
45
46 private static instance: LiveManager
47
48 private readonly muxingSessions = new Map<string, MuxingSession>()
49 private readonly videoSessions = new Map<number, string>()
50 // Values are Date().getTime()
51 private readonly watchersPerVideo = new Map<number, number[]>()
52
53 private rtmpServer: Server
54
55 private constructor () {
56 }
57
58 init () {
59 const events = this.getContext().nodeEvent
60 events.on('postPublish', (sessionId: string, streamPath: string) => {
61 logger.debug('RTMP received stream', { id: sessionId, streamPath, ...lTags(sessionId) })
62
63 const splittedPath = streamPath.split('/')
64 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
65 logger.warn('Live path is incorrect.', { streamPath, ...lTags(sessionId) })
66 return this.abortSession(sessionId)
67 }
68
69 this.handleSession(sessionId, streamPath, splittedPath[2])
70 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
71 })
72
73 events.on('donePublish', sessionId => {
74 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
75 })
76
77 registerConfigChangedHandler(() => {
78 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
79 this.run()
80 return
81 }
82
83 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
84 this.stop()
85 }
86 })
87
88 // Cleanup broken lives, that were terminated by a server restart for example
89 this.handleBrokenLives()
90 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
91
92 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
93 }
94
95 run () {
96 logger.info('Running RTMP server on port %d', config.rtmp.port, lTags())
97
98 this.rtmpServer = createServer(socket => {
99 const session = new NodeRtmpSession(config, socket)
100
101 session.run()
102 })
103
104 this.rtmpServer.on('error', err => {
105 logger.error('Cannot run RTMP server.', { err, ...lTags() })
106 })
107
108 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
109 }
110
111 stop () {
112 logger.info('Stopping RTMP server.', lTags())
113
114 this.rtmpServer.close()
115 this.rtmpServer = undefined
116
117 // Sessions is an object
118 this.getContext().sessions.forEach((session: any) => {
119 if (session instanceof NodeRtmpSession) {
120 session.stop()
121 }
122 })
123 }
124
125 isRunning () {
126 return !!this.rtmpServer
127 }
128
129 stopSessionOf (videoId: number) {
130 const sessionId = this.videoSessions.get(videoId)
131 if (!sessionId) return
132
133 this.videoSessions.delete(videoId)
134 this.abortSession(sessionId)
135 }
136
137 addViewTo (videoId: number) {
138 if (this.videoSessions.has(videoId) === false) return
139
140 let watchers = this.watchersPerVideo.get(videoId)
141
142 if (!watchers) {
143 watchers = []
144 this.watchersPerVideo.set(videoId, watchers)
145 }
146
147 watchers.push(new Date().getTime())
148 }
149
150 private getContext () {
151 return context
152 }
153
154 private abortSession (sessionId: string) {
155 const session = this.getContext().sessions.get(sessionId)
156 if (session) {
157 session.stop()
158 this.getContext().sessions.delete(sessionId)
159 }
160
161 const muxingSession = this.muxingSessions.get(sessionId)
609a4442 162 if (muxingSession) {
e466544f 163 // Muxing session will fire and event so we correctly cleanup the session
609a4442 164 muxingSession.abort()
609a4442
C
165
166 this.muxingSessions.delete(sessionId)
167 }
8ebf2a5d
C
168 }
169
170 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
171 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
172 if (!videoLive) {
173 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
174 return this.abortSession(sessionId)
175 }
176
177 const video = videoLive.Video
178 if (video.isBlacklisted()) {
179 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
180 return this.abortSession(sessionId)
181 }
182
183 // Cleanup old potential live files (could happen with a permanent live)
184 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
185
186 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
187 if (oldStreamingPlaylist) {
188 await cleanupLive(video, oldStreamingPlaylist)
189 }
190
191 this.videoSessions.set(video.id, sessionId)
192
193 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
194
195 const [ { videoFileResolution }, fps ] = await Promise.all([
196 getVideoFileResolution(rtmpUrl),
197 getVideoFileFPS(rtmpUrl)
198 ])
199
200 const allResolutions = this.buildAllResolutionsToTranscode(videoFileResolution)
201
202 logger.info(
203 'Will mux/transcode live video of original resolution %d.', videoFileResolution,
204 { allResolutions, ...lTags(sessionId, video.uuid) }
205 )
206
207 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
208
209 return this.runMuxingSession({
210 sessionId,
211 videoLive,
212 streamingPlaylist,
213 rtmpUrl,
214 fps,
215 allResolutions
216 })
217 }
218
219 private async runMuxingSession (options: {
220 sessionId: string
221 videoLive: MVideoLiveVideo
222 streamingPlaylist: MStreamingPlaylistVideo
223 rtmpUrl: string
224 fps: number
225 allResolutions: number[]
226 }) {
227 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, rtmpUrl } = options
228 const videoUUID = videoLive.Video.uuid
229 const localLTags = lTags(sessionId, videoUUID)
230
231 const user = await UserModel.loadByLiveId(videoLive.id)
232 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
233
234 const muxingSession = new MuxingSession({
235 context: this.getContext(),
236 user,
237 sessionId,
238 videoLive,
239 streamingPlaylist,
240 rtmpUrl,
241 fps,
242 allResolutions
243 })
244
245 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
246
247 muxingSession.on('bad-socket-health', ({ videoId }) => {
248 logger.error(
249 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
250 ' Stopping session of video %s.', videoUUID,
251 localLTags
252 )
253
254 this.stopSessionOf(videoId)
255 })
256
257 muxingSession.on('duration-exceeded', ({ videoId }) => {
258 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
259
260 this.stopSessionOf(videoId)
261 })
262
263 muxingSession.on('quota-exceeded', ({ videoId }) => {
264 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
265
266 this.stopSessionOf(videoId)
267 })
268
269 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
270 muxingSession.on('ffmpeg-end', ({ videoId }) => {
271 this.onMuxingFFmpegEnd(videoId)
272 })
273
274 muxingSession.on('after-cleanup', ({ videoId }) => {
275 this.muxingSessions.delete(sessionId)
276
609a4442
C
277 muxingSession.destroy()
278
8ebf2a5d
C
279 return this.onAfterMuxingCleanup(videoId)
280 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
281 })
282
283 this.muxingSessions.set(sessionId, muxingSession)
284
285 muxingSession.runMuxing()
286 .catch(err => {
287 logger.error('Cannot run muxing.', { err, ...localLTags })
288 this.abortSession(sessionId)
289 })
290 }
291
292 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
293 const videoId = live.videoId
294
295 try {
296 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
297
298 logger.info('Will publish and federate live %s.', video.url, localLTags)
299
300 video.state = VideoState.PUBLISHED
301 await video.save()
302
303 live.Video = video
304
305 setTimeout(() => {
306 federateVideoIfNeeded(video, false)
307 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
308
309 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
310 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
311 } catch (err) {
312 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
313 }
314 }
315
316 private onMuxingFFmpegEnd (videoId: number) {
317 this.watchersPerVideo.delete(videoId)
318 this.videoSessions.delete(videoId)
319 }
320
321 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
322 try {
323 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
324 if (!fullVideo) return
325
326 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
327
328 if (!live.permanentLive) {
329 JobQueue.Instance.createJob({
330 type: 'video-live-ending',
331 payload: {
332 videoId: fullVideo.id
333 }
334 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
335
336 fullVideo.state = VideoState.LIVE_ENDED
337 } else {
338 fullVideo.state = VideoState.WAITING_FOR_LIVE
339 }
340
341 await fullVideo.save()
342
343 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
344
345 await federateVideoIfNeeded(fullVideo, false)
346 } catch (err) {
347 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
348 }
349 }
350
351 private async updateLiveViews () {
352 if (!this.isRunning()) return
353
354 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
355
356 for (const videoId of this.watchersPerVideo.keys()) {
357 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
358
359 const watchers = this.watchersPerVideo.get(videoId)
360
361 const numWatchers = watchers.length
362
363 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
364 video.views = numWatchers
365 await video.save()
366
367 await federateVideoIfNeeded(video, false)
368
369 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
370
371 // Only keep not expired watchers
372 const newWatchers = watchers.filter(w => w > notBefore)
373 this.watchersPerVideo.set(videoId, newWatchers)
374
375 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
376 }
377 }
378
379 private async handleBrokenLives () {
380 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
381
382 for (const uuid of videoUUIDs) {
383 await this.onAfterMuxingCleanup(uuid, true)
384 }
385 }
386
387 private buildAllResolutionsToTranscode (originResolution: number) {
388 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
389 ? computeResolutionsToTranscode(originResolution, 'live')
390 : []
391
392 return resolutionsEnabled.concat([ originResolution ])
393 }
394
395 private async createLivePlaylist (video: MVideo, allResolutions: number[]) {
396 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
397 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
398 videoId: video.id,
399 playlistUrl,
400 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
401 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions),
402 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
403
404 type: VideoStreamingPlaylistType.HLS
405 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
406
407 return Object.assign(videoStreamingPlaylist, { Video: video })
408 }
409
410 static get Instance () {
411 return this.instance || (this.instance = new this())
412 }
413}
414
415// ---------------------------------------------------------------------------
416
417export {
418 LiveManager
419}