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