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'
7 computeResolutionsToTranscode,
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'
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')
35 // Disable node media server logs
36 nodeMediaServerLogger.setLogType(0)
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
48 const lTags = loggerTagsFactory('live')
52 private static instance: LiveManager
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[]>()
59 private rtmpServer: Server
60 private rtmpsServer: ServerTLS
62 private running = false
64 private constructor () {
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) })
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)
78 const session = this.getContext().sessions.get(sessionId)
80 this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2])
81 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
84 events.on('donePublish', sessionId => {
85 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
88 registerConfigChangedHandler(() => {
89 if (!this.running && CONFIG.LIVE.ENABLED === true) {
90 this.run().catch(err => logger.error('Cannot run live server.', { err }))
94 if (this.running && CONFIG.LIVE.ENABLED === false) {
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() }))
103 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
109 if (CONFIG.LIVE.RTMP.ENABLED) {
110 logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags())
112 this.rtmpServer = createServer(socket => {
113 const session = new NodeRtmpSession(config, socket)
115 session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT
119 this.rtmpServer.on('error', err => {
120 logger.error('Cannot run RTMP server.', { err, ...lTags() })
123 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
126 if (CONFIG.LIVE.RTMPS.ENABLED) {
127 logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags())
129 const [ key, cert ] = await Promise.all([
130 readFile(CONFIG.LIVE.RTMPS.KEY_FILE),
131 readFile(CONFIG.LIVE.RTMPS.CERT_FILE)
133 const serverOptions = { key, cert }
135 this.rtmpsServer = createServerTLS(serverOptions, socket => {
136 const session = new NodeRtmpSession(config, socket)
138 session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT
142 this.rtmpsServer.on('error', err => {
143 logger.error('Cannot run RTMPS server.', { err, ...lTags() })
146 this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT)
153 if (this.rtmpServer) {
154 logger.info('Stopping RTMP server.', lTags())
156 this.rtmpServer.close()
157 this.rtmpServer = undefined
160 if (this.rtmpsServer) {
161 logger.info('Stopping RTMPS server.', lTags())
163 this.rtmpsServer.close()
164 this.rtmpsServer = undefined
167 // Sessions is an object
168 this.getContext().sessions.forEach((session: any) => {
169 if (session instanceof NodeRtmpSession) {
176 return !!this.rtmpServer
179 stopSessionOf (videoId: number) {
180 const sessionId = this.videoSessions.get(videoId)
181 if (!sessionId) return
183 this.videoSessions.delete(videoId)
184 this.abortSession(sessionId)
187 addViewTo (videoId: number) {
188 if (this.videoSessions.has(videoId) === false) return
190 let watchers = this.watchersPerVideo.get(videoId)
194 this.watchersPerVideo.set(videoId, watchers)
197 watchers.push(new Date().getTime())
200 private getContext () {
204 private abortSession (sessionId: string) {
205 const session = this.getContext().sessions.get(sessionId)
208 this.getContext().sessions.delete(sessionId)
211 const muxingSession = this.muxingSessions.get(sessionId)
213 // Muxing session will fire and event so we correctly cleanup the session
214 muxingSession.abort()
216 this.muxingSessions.delete(sessionId)
220 private async handleSession (sessionId: string, inputUrl: string, streamKey: string) {
221 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
223 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
224 return this.abortSession(sessionId)
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)
233 // Cleanup old potential live files (could happen with a permanent live)
234 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
236 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
237 if (oldStreamingPlaylist) {
238 await cleanupLive(video, oldStreamingPlaylist)
241 this.videoSessions.set(video.id, sessionId)
243 const now = Date.now()
244 const probe = await ffprobePromise(inputUrl)
246 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
247 getVideoFileResolution(inputUrl, probe),
248 getVideoFileFPS(inputUrl, probe),
249 getVideoFileBitrate(inputUrl, probe)
253 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
254 inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
257 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
260 'Will mux/transcode live video of original resolution %d.', resolution,
261 { allResolutions, ...lTags(sessionId, video.uuid) }
264 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
266 return this.runMuxingSession({
278 private async runMuxingSession (options: {
280 videoLive: MVideoLiveVideo
281 streamingPlaylist: MStreamingPlaylistVideo
286 allResolutions: number[]
288 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options
289 const videoUUID = videoLive.Video.uuid
290 const localLTags = lTags(sessionId, videoUUID)
292 const user = await UserModel.loadByLiveId(videoLive.id)
293 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
295 const muxingSession = new MuxingSession({
296 context: this.getContext(),
308 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
310 muxingSession.on('bad-socket-health', ({ videoId }) => {
312 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
313 ' Stopping session of video %s.', videoUUID,
317 this.stopSessionOf(videoId)
320 muxingSession.on('duration-exceeded', ({ videoId }) => {
321 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
323 this.stopSessionOf(videoId)
326 muxingSession.on('quota-exceeded', ({ videoId }) => {
327 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
329 this.stopSessionOf(videoId)
332 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
333 muxingSession.on('ffmpeg-end', ({ videoId }) => {
334 this.onMuxingFFmpegEnd(videoId)
337 muxingSession.on('after-cleanup', ({ videoId }) => {
338 this.muxingSessions.delete(sessionId)
340 muxingSession.destroy()
342 return this.onAfterMuxingCleanup(videoId)
343 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
346 this.muxingSessions.set(sessionId, muxingSession)
348 muxingSession.runMuxing()
350 logger.error('Cannot run muxing.', { err, ...localLTags })
351 this.abortSession(sessionId)
355 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
356 const videoId = live.videoId
359 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
361 logger.info('Will publish and federate live %s.', video.url, localLTags)
363 video.state = VideoState.PUBLISHED
369 federateVideoIfNeeded(video, false)
370 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
372 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
373 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
375 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
379 private onMuxingFFmpegEnd (videoId: number) {
380 this.watchersPerVideo.delete(videoId)
381 this.videoSessions.delete(videoId)
384 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
386 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
387 if (!fullVideo) return
389 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
391 if (!live.permanentLive) {
392 JobQueue.Instance.createJob({
393 type: 'video-live-ending',
395 videoId: fullVideo.id
397 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
399 fullVideo.state = VideoState.LIVE_ENDED
401 fullVideo.state = VideoState.WAITING_FOR_LIVE
404 await fullVideo.save()
406 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
408 await federateVideoIfNeeded(fullVideo, false)
410 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
414 private async updateLiveViews () {
415 if (!this.isRunning()) return
417 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
419 for (const videoId of this.watchersPerVideo.keys()) {
420 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
422 const watchers = this.watchersPerVideo.get(videoId)
424 const numWatchers = watchers.length
426 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
427 video.views = numWatchers
430 await federateVideoIfNeeded(video, false)
432 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
434 // Only keep not expired watchers
435 const newWatchers = watchers.filter(w => w > notBefore)
436 this.watchersPerVideo.set(videoId, newWatchers)
438 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
442 private async handleBrokenLives () {
443 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
445 for (const uuid of videoUUIDs) {
446 await this.onAfterMuxingCleanup(uuid, true)
450 private buildAllResolutionsToTranscode (originResolution: number) {
451 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
452 ? computeResolutionsToTranscode(originResolution, 'live')
455 return resolutionsEnabled.concat([ originResolution ])
458 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
459 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
461 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
462 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
464 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
465 playlist.type = VideoStreamingPlaylistType.HLS
467 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
469 return playlist.save()
472 static get Instance () {
473 return this.instance || (this.instance = new this())
477 // ---------------------------------------------------------------------------