2 import { createServer, Server } from 'net'
3 import { isTestInstance } from '@server/helpers/core-utils'
5 computeResolutionsToTranscode,
10 } from '@server/helpers/ffprobe-utils'
11 import { logger, loggerTagsFactory } from '@server/helpers/logger'
12 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
13 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME } from '@server/initializers/constants'
14 import { UserModel } from '@server/models/user/user'
15 import { VideoModel } from '@server/models/video/video'
16 import { VideoLiveModel } from '@server/models/video/video-live'
17 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
18 import { MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models'
19 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
20 import { federateVideoIfNeeded } from '../activitypub/videos'
21 import { JobQueue } from '../job-queue'
22 import { PeerTubeSocket } from '../peertube-socket'
23 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../paths'
24 import { LiveQuotaStore } from './live-quota-store'
25 import { LiveSegmentShaStore } from './live-segment-sha-store'
26 import { cleanupLive } from './live-utils'
27 import { MuxingSession } from './shared'
29 const NodeRtmpSession = require('node-media-server/src/node_rtmp_session')
30 const context = require('node-media-server/src/node_core_ctx')
31 const nodeMediaServerLogger = require('node-media-server/src/node_core_logger')
33 // Disable node media server logs
34 nodeMediaServerLogger.setLogType(0)
38 port: CONFIG.LIVE.RTMP.PORT,
39 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
40 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
41 ping: VIDEO_LIVE.RTMP.PING,
42 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
49 const lTags = loggerTagsFactory('live')
53 private static instance: LiveManager
55 private readonly muxingSessions = new Map<string, MuxingSession>()
56 private readonly videoSessions = new Map<number, string>()
57 // Values are Date().getTime()
58 private readonly watchersPerVideo = new Map<number, number[]>()
60 private rtmpServer: Server
62 private constructor () {
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) })
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)
76 this.handleSession(sessionId, streamPath, splittedPath[2])
77 .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) }))
80 events.on('donePublish', sessionId => {
81 logger.info('Live session ended.', { sessionId, ...lTags(sessionId) })
84 registerConfigChangedHandler(() => {
85 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
90 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
95 // Cleanup broken lives, that were terminated by a server restart for example
96 this.handleBrokenLives()
97 .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() }))
99 setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE)
103 logger.info('Running RTMP server on port %d', config.rtmp.port, lTags())
105 this.rtmpServer = createServer(socket => {
106 const session = new NodeRtmpSession(config, socket)
111 this.rtmpServer.on('error', err => {
112 logger.error('Cannot run RTMP server.', { err, ...lTags() })
115 this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
119 logger.info('Stopping RTMP server.', lTags())
121 this.rtmpServer.close()
122 this.rtmpServer = undefined
124 // Sessions is an object
125 this.getContext().sessions.forEach((session: any) => {
126 if (session instanceof NodeRtmpSession) {
133 return !!this.rtmpServer
136 stopSessionOf (videoId: number) {
137 const sessionId = this.videoSessions.get(videoId)
138 if (!sessionId) return
140 this.videoSessions.delete(videoId)
141 this.abortSession(sessionId)
144 addViewTo (videoId: number) {
145 if (this.videoSessions.has(videoId) === false) return
147 let watchers = this.watchersPerVideo.get(videoId)
151 this.watchersPerVideo.set(videoId, watchers)
154 watchers.push(new Date().getTime())
157 private getContext () {
161 private abortSession (sessionId: string) {
162 const session = this.getContext().sessions.get(sessionId)
165 this.getContext().sessions.delete(sessionId)
168 const muxingSession = this.muxingSessions.get(sessionId)
170 // Muxing session will fire and event so we correctly cleanup the session
171 muxingSession.abort()
173 this.muxingSessions.delete(sessionId)
177 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
178 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
180 logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId))
181 return this.abortSession(sessionId)
184 const video = videoLive.Video
185 if (video.isBlacklisted()) {
186 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey, lTags(sessionId, video.uuid))
187 return this.abortSession(sessionId)
190 // Cleanup old potential live files (could happen with a permanent live)
191 LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid)
193 const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
194 if (oldStreamingPlaylist) {
195 await cleanupLive(video, oldStreamingPlaylist)
198 this.videoSessions.set(video.id, sessionId)
200 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
202 const now = Date.now()
203 const probe = await ffprobePromise(rtmpUrl)
205 const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([
206 getVideoFileResolution(rtmpUrl, probe),
207 getVideoFileFPS(rtmpUrl, probe),
208 getVideoFileBitrate(rtmpUrl, probe)
212 '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)',
213 rtmpUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid)
216 const allResolutions = this.buildAllResolutionsToTranscode(resolution)
219 'Will mux/transcode live video of original resolution %d.', resolution,
220 { allResolutions, ...lTags(sessionId, video.uuid) }
223 const streamingPlaylist = await this.createLivePlaylist(video, allResolutions)
225 return this.runMuxingSession({
237 private async runMuxingSession (options: {
239 videoLive: MVideoLiveVideo
240 streamingPlaylist: MStreamingPlaylistVideo
245 allResolutions: number[]
247 const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, rtmpUrl } = options
248 const videoUUID = videoLive.Video.uuid
249 const localLTags = lTags(sessionId, videoUUID)
251 const user = await UserModel.loadByLiveId(videoLive.id)
252 LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id)
254 const muxingSession = new MuxingSession({
255 context: this.getContext(),
267 muxingSession.on('master-playlist-created', () => this.publishAndFederateLive(videoLive, localLTags))
269 muxingSession.on('bad-socket-health', ({ videoId }) => {
271 'Too much data in client socket stream (ffmpeg is too slow to transcode the video).' +
272 ' Stopping session of video %s.', videoUUID,
276 this.stopSessionOf(videoId)
279 muxingSession.on('duration-exceeded', ({ videoId }) => {
280 logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags)
282 this.stopSessionOf(videoId)
285 muxingSession.on('quota-exceeded', ({ videoId }) => {
286 logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags)
288 this.stopSessionOf(videoId)
291 muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId))
292 muxingSession.on('ffmpeg-end', ({ videoId }) => {
293 this.onMuxingFFmpegEnd(videoId)
296 muxingSession.on('after-cleanup', ({ videoId }) => {
297 this.muxingSessions.delete(sessionId)
299 muxingSession.destroy()
301 return this.onAfterMuxingCleanup(videoId)
302 .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags }))
305 this.muxingSessions.set(sessionId, muxingSession)
307 muxingSession.runMuxing()
309 logger.error('Cannot run muxing.', { err, ...localLTags })
310 this.abortSession(sessionId)
314 private async publishAndFederateLive (live: MVideoLiveVideo, localLTags: { tags: string[] }) {
315 const videoId = live.videoId
318 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
320 logger.info('Will publish and federate live %s.', video.url, localLTags)
322 video.state = VideoState.PUBLISHED
328 federateVideoIfNeeded(video, false)
329 .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }))
331 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
332 }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION)
334 logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
338 private onMuxingFFmpegEnd (videoId: number) {
339 this.watchersPerVideo.delete(videoId)
340 this.videoSessions.delete(videoId)
343 private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) {
345 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID)
346 if (!fullVideo) return
348 const live = await VideoLiveModel.loadByVideoId(fullVideo.id)
350 if (!live.permanentLive) {
351 JobQueue.Instance.createJob({
352 type: 'video-live-ending',
354 videoId: fullVideo.id
356 }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
358 fullVideo.state = VideoState.LIVE_ENDED
360 fullVideo.state = VideoState.WAITING_FOR_LIVE
363 await fullVideo.save()
365 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
367 await federateVideoIfNeeded(fullVideo, false)
369 logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) })
373 private async updateLiveViews () {
374 if (!this.isRunning()) return
376 if (!isTestInstance()) logger.info('Updating live video views.', lTags())
378 for (const videoId of this.watchersPerVideo.keys()) {
379 const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE
381 const watchers = this.watchersPerVideo.get(videoId)
383 const numWatchers = watchers.length
385 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
386 video.views = numWatchers
389 await federateVideoIfNeeded(video, false)
391 PeerTubeSocket.Instance.sendVideoViewsUpdate(video)
393 // Only keep not expired watchers
394 const newWatchers = watchers.filter(w => w > notBefore)
395 this.watchersPerVideo.set(videoId, newWatchers)
397 logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags())
401 private async handleBrokenLives () {
402 const videoUUIDs = await VideoModel.listPublishedLiveUUIDs()
404 for (const uuid of videoUUIDs) {
405 await this.onAfterMuxingCleanup(uuid, true)
409 private buildAllResolutionsToTranscode (originResolution: number) {
410 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
411 ? computeResolutionsToTranscode(originResolution, 'live')
414 return resolutionsEnabled.concat([ originResolution ])
417 private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise<MStreamingPlaylistVideo> {
418 const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video)
420 playlist.playlistFilename = generateHLSMasterPlaylistFilename(true)
421 playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true)
423 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
424 playlist.type = VideoStreamingPlaylistType.HLS
426 playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions)
428 return playlist.save()
431 static get Instance () {
432 return this.instance || (this.instance = new this())
436 // ---------------------------------------------------------------------------