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