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