X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Flib%2Flive%2Flive-manager.ts;h=d499b4b1af3e245d593fc4af21cb3fa5ab7aa928;hb=b6e2b5df73d3b67e275000f612907859c39d90d1;hp=014cd3fcf12d38abf476a79fc3711e29fa8bbb0b;hpb=cf21b2cbef61929177b9c09b5e017c3b7eb8535d;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/lib/live/live-manager.ts b/server/lib/live/live-manager.ts index 014cd3fcf..d499b4b1a 100644 --- a/server/lib/live/live-manager.ts +++ b/server/lib/live/live-manager.ts @@ -1,27 +1,38 @@ +import { readdir, readFile } from 'fs-extra' import { createServer, Server } from 'net' -import { isTestInstance } from '@server/helpers/core-utils' -import { computeResolutionsToTranscode, getVideoFileFPS, getVideoFileResolution } from '@server/helpers/ffprobe-utils' +import { join } from 'path' +import { createServer as createServerTLS, Server as ServerTLS } from 'tls' +import { + computeLowerResolutionsToTranscode, + ffprobePromise, + getLiveSegmentTime, + getVideoStreamBitrate, + getVideoStreamDimensionsInfo, + getVideoStreamFPS +} from '@server/helpers/ffmpeg' import { logger, loggerTagsFactory } from '@server/helpers/logger' import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config' -import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, VIEW_LIFETIME, WEBSERVER } from '@server/initializers/constants' +import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/constants' import { UserModel } from '@server/models/user/user' import { VideoModel } from '@server/models/video/video' import { VideoLiveModel } from '@server/models/video/video-live' +import { VideoLiveSessionModel } from '@server/models/video/video-live-session' import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' -import { MStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoLiveVideo } from '@server/types/models' -import { VideoState, VideoStreamingPlaylistType } from '@shared/models' +import { MStreamingPlaylistVideo, MVideo, MVideoLiveSession, MVideoLiveVideo } from '@server/types/models' +import { wait } from '@shared/core-utils' +import { LiveVideoError, VideoState, VideoStreamingPlaylistType } from '@shared/models' import { federateVideoIfNeeded } from '../activitypub/videos' import { JobQueue } from '../job-queue' +import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '../paths' import { PeerTubeSocket } from '../peertube-socket' import { LiveQuotaStore } from './live-quota-store' -import { LiveSegmentShaStore } from './live-segment-sha-store' -import { cleanupLive } from './live-utils' +import { cleanupPermanentLive } from './live-utils' import { MuxingSession } from './shared' -const NodeRtmpSession = require('node-media-server/node_rtmp_session') -const context = require('node-media-server/node_core_ctx') -const nodeMediaServerLogger = require('node-media-server/node_core_logger') +const NodeRtmpSession = require('node-media-server/src/node_rtmp_session') +const context = require('node-media-server/src/node_core_ctx') +const nodeMediaServerLogger = require('node-media-server/src/node_core_logger') // Disable node media server logs nodeMediaServerLogger.setLogType(0) @@ -33,9 +44,6 @@ const config = { gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE, ping: VIDEO_LIVE.RTMP.PING, ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT - }, - transcoding: { - ffmpeg: 'ffmpeg' } } @@ -47,10 +55,11 @@ class LiveManager { private readonly muxingSessions = new Map() private readonly videoSessions = new Map() - // Values are Date().getTime() - private readonly watchersPerVideo = new Map() private rtmpServer: Server + private rtmpsServer: ServerTLS + + private running = false private constructor () { } @@ -66,7 +75,9 @@ class LiveManager { return this.abortSession(sessionId) } - this.handleSession(sessionId, streamPath, splittedPath[2]) + const session = this.getContext().sessions.get(sessionId) + + this.handleSession(sessionId, session.inputOriginUrl + streamPath, splittedPath[2]) .catch(err => logger.error('Cannot handle sessions.', { err, ...lTags(sessionId) })) }) @@ -75,12 +86,12 @@ class LiveManager { }) registerConfigChangedHandler(() => { - if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) { - this.run() + if (!this.running && CONFIG.LIVE.ENABLED === true) { + this.run().catch(err => logger.error('Cannot run live server.', { err })) return } - if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) { + if (this.running && CONFIG.LIVE.ENABLED === false) { this.stop() } }) @@ -88,31 +99,68 @@ class LiveManager { // Cleanup broken lives, that were terminated by a server restart for example this.handleBrokenLives() .catch(err => logger.error('Cannot handle broken lives.', { err, ...lTags() })) - - setInterval(() => this.updateLiveViews(), VIEW_LIFETIME.LIVE) } - run () { - logger.info('Running RTMP server on port %d', config.rtmp.port, lTags()) + async run () { + this.running = true - this.rtmpServer = createServer(socket => { - const session = new NodeRtmpSession(config, socket) + if (CONFIG.LIVE.RTMP.ENABLED) { + logger.info('Running RTMP server on port %d', CONFIG.LIVE.RTMP.PORT, lTags()) - session.run() - }) + this.rtmpServer = createServer(socket => { + const session = new NodeRtmpSession(config, socket) - this.rtmpServer.on('error', err => { - logger.error('Cannot run RTMP server.', { err, ...lTags() }) - }) + session.inputOriginUrl = 'rtmp://127.0.0.1:' + CONFIG.LIVE.RTMP.PORT + session.run() + }) + + this.rtmpServer.on('error', err => { + logger.error('Cannot run RTMP server.', { err, ...lTags() }) + }) + + this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME) + } - this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT) + if (CONFIG.LIVE.RTMPS.ENABLED) { + logger.info('Running RTMPS server on port %d', CONFIG.LIVE.RTMPS.PORT, lTags()) + + const [ key, cert ] = await Promise.all([ + readFile(CONFIG.LIVE.RTMPS.KEY_FILE), + readFile(CONFIG.LIVE.RTMPS.CERT_FILE) + ]) + const serverOptions = { key, cert } + + this.rtmpsServer = createServerTLS(serverOptions, socket => { + const session = new NodeRtmpSession(config, socket) + + session.inputOriginUrl = 'rtmps://127.0.0.1:' + CONFIG.LIVE.RTMPS.PORT + session.run() + }) + + this.rtmpsServer.on('error', err => { + logger.error('Cannot run RTMPS server.', { err, ...lTags() }) + }) + + this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME) + } } stop () { - logger.info('Stopping RTMP server.', lTags()) + this.running = false + + if (this.rtmpServer) { + logger.info('Stopping RTMP server.', lTags()) - this.rtmpServer.close() - this.rtmpServer = undefined + this.rtmpServer.close() + this.rtmpServer = undefined + } + + if (this.rtmpsServer) { + logger.info('Stopping RTMPS server.', lTags()) + + this.rtmpsServer.close() + this.rtmpsServer = undefined + } // Sessions is an object this.getContext().sessions.forEach((session: any) => { @@ -126,27 +174,17 @@ class LiveManager { return !!this.rtmpServer } - stopSessionOf (videoId: number) { + stopSessionOf (videoId: number, error: LiveVideoError | null) { const sessionId = this.videoSessions.get(videoId) if (!sessionId) return + this.saveEndingSession(videoId, error) + .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) })) + this.videoSessions.delete(videoId) this.abortSession(sessionId) } - addViewTo (videoId: number) { - if (this.videoSessions.has(videoId) === false) return - - let watchers = this.watchersPerVideo.get(videoId) - - if (!watchers) { - watchers = [] - this.watchersPerVideo.set(videoId, watchers) - } - - watchers.push(new Date().getTime()) - } - private getContext () { return context } @@ -167,7 +205,7 @@ class LiveManager { } } - private async handleSession (sessionId: string, streamPath: string, streamKey: string) { + private async handleSession (sessionId: string, inputUrl: string, streamKey: string) { const videoLive = await VideoLiveModel.loadByStreamKey(streamKey) if (!videoLive) { logger.warn('Unknown live video with stream key %s.', streamKey, lTags(sessionId)) @@ -180,27 +218,34 @@ class LiveManager { return this.abortSession(sessionId) } - // Cleanup old potential live files (could happen with a permanent live) - LiveSegmentShaStore.Instance.cleanupShaSegments(video.uuid) - + // Cleanup old potential live (could happen with a permanent live) const oldStreamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) if (oldStreamingPlaylist) { - await cleanupLive(video, oldStreamingPlaylist) + if (!videoLive.permanentLive) throw new Error('Found previous session in a non permanent live: ' + video.uuid) + + await cleanupPermanentLive(video, oldStreamingPlaylist) } this.videoSessions.set(video.id, sessionId) - const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath + const now = Date.now() + const probe = await ffprobePromise(inputUrl) - const [ { videoFileResolution }, fps ] = await Promise.all([ - getVideoFileResolution(rtmpUrl), - getVideoFileFPS(rtmpUrl) + const [ { resolution, ratio }, fps, bitrate ] = await Promise.all([ + getVideoStreamDimensionsInfo(inputUrl, probe), + getVideoStreamFPS(inputUrl, probe), + getVideoStreamBitrate(inputUrl, probe) ]) - const allResolutions = this.buildAllResolutionsToTranscode(videoFileResolution) + logger.info( + '%s probing took %d ms (bitrate: %d, fps: %d, resolution: %d)', + inputUrl, Date.now() - now, bitrate, fps, resolution, lTags(sessionId, video.uuid) + ) + + const allResolutions = this.buildAllResolutionsToTranscode(resolution) logger.info( - 'Will mux/transcode live video of original resolution %d.', videoFileResolution, + 'Will mux/transcode live video of original resolution %d.', resolution, { allResolutions, ...lTags(sessionId, video.uuid) } ) @@ -210,8 +255,10 @@ class LiveManager { sessionId, videoLive, streamingPlaylist, - rtmpUrl, + inputUrl, fps, + bitrate, + ratio, allResolutions }) } @@ -220,14 +267,18 @@ class LiveManager { sessionId: string videoLive: MVideoLiveVideo streamingPlaylist: MStreamingPlaylistVideo - rtmpUrl: string + inputUrl: string fps: number + bitrate: number + ratio: number allResolutions: number[] }) { - const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, rtmpUrl } = options + const { sessionId, videoLive, streamingPlaylist, allResolutions, fps, bitrate, ratio, inputUrl } = options const videoUUID = videoLive.Video.uuid const localLTags = lTags(sessionId, videoUUID) + const liveSession = await this.saveStartingSession(videoLive) + const user = await UserModel.loadByLiveId(videoLive.id) LiveQuotaStore.Instance.addNewLive(user.id, videoLive.id) @@ -237,7 +288,9 @@ class LiveManager { sessionId, videoLive, streamingPlaylist, - rtmpUrl, + inputUrl, + bitrate, + ratio, fps, allResolutions }) @@ -251,32 +304,37 @@ class LiveManager { localLTags ) - this.stopSessionOf(videoId) + this.stopSessionOf(videoId, LiveVideoError.BAD_SOCKET_HEALTH) }) muxingSession.on('duration-exceeded', ({ videoId }) => { logger.info('Stopping session of %s: max duration exceeded.', videoUUID, localLTags) - this.stopSessionOf(videoId) + this.stopSessionOf(videoId, LiveVideoError.DURATION_EXCEEDED) }) muxingSession.on('quota-exceeded', ({ videoId }) => { logger.info('Stopping session of %s: user quota exceeded.', videoUUID, localLTags) - this.stopSessionOf(videoId) + this.stopSessionOf(videoId, LiveVideoError.QUOTA_EXCEEDED) + }) + + muxingSession.on('ffmpeg-error', ({ videoId }) => { + this.stopSessionOf(videoId, LiveVideoError.FFMPEG_ERROR) }) - muxingSession.on('ffmpeg-error', ({ sessionId }) => this.abortSession(sessionId)) muxingSession.on('ffmpeg-end', ({ videoId }) => { - this.onMuxingFFmpegEnd(videoId) + this.onMuxingFFmpegEnd(videoId, sessionId) }) muxingSession.on('after-cleanup', ({ videoId }) => { this.muxingSessions.delete(sessionId) + LiveQuotaStore.Instance.removeLive(user.id, videoLive.id) + muxingSession.destroy() - return this.onAfterMuxingCleanup(videoId) + return this.onAfterMuxingCleanup({ videoId, liveSession }) .catch(err => logger.error('Error in end transmuxing.', { err, ...localLTags })) }) @@ -298,81 +356,80 @@ class LiveManager { logger.info('Will publish and federate live %s.', video.url, localLTags) video.state = VideoState.PUBLISHED + video.publishedAt = new Date() await video.save() live.Video = video - setTimeout(() => { - federateVideoIfNeeded(video, false) - .catch(err => logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags })) + await wait(getLiveSegmentTime(live.latencyMode) * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) + + try { + await federateVideoIfNeeded(video, false) + } catch (err) { + logger.error('Cannot federate live video %s.', video.url, { err, ...localLTags }) + } - PeerTubeSocket.Instance.sendVideoLiveNewState(video) - }, VIDEO_LIVE.SEGMENT_TIME_SECONDS * 1000 * VIDEO_LIVE.EDGE_LIVE_DELAY_SEGMENTS_NOTIFICATION) + PeerTubeSocket.Instance.sendVideoLiveNewState(video) } catch (err) { logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags }) } } - private onMuxingFFmpegEnd (videoId: number) { - this.watchersPerVideo.delete(videoId) + private onMuxingFFmpegEnd (videoId: number, sessionId: string) { this.videoSessions.delete(videoId) + + this.saveEndingSession(videoId, null) + .catch(err => logger.error('Cannot save ending session.', { err, ...lTags(sessionId) })) } - private async onAfterMuxingCleanup (videoUUID: string, cleanupNow = false) { + private async onAfterMuxingCleanup (options: { + videoId: number | string + liveSession?: MVideoLiveSession + cleanupNow?: boolean // Default false + }) { + const { videoId, liveSession: liveSessionArg, cleanupNow = false } = options + try { - const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoUUID) + const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) if (!fullVideo) return const live = await VideoLiveModel.loadByVideoId(fullVideo.id) - if (!live.permanentLive) { - JobQueue.Instance.createJob({ - type: 'video-live-ending', - payload: { - videoId: fullVideo.id - } - }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) - - fullVideo.state = VideoState.LIVE_ENDED - } else { - fullVideo.state = VideoState.WAITING_FOR_LIVE - } + const liveSession = liveSessionArg ?? await VideoLiveSessionModel.findCurrentSessionOf(fullVideo.id) - await fullVideo.save() - - PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) - - await federateVideoIfNeeded(fullVideo, false) - } catch (err) { - logger.error('Cannot save/federate new video state of live streaming of video %d.', videoUUID, { err, ...lTags(videoUUID) }) - } - } - - private async updateLiveViews () { - if (!this.isRunning()) return + // On server restart during a live + if (!liveSession.endDate) { + liveSession.endDate = new Date() + await liveSession.save() + } - if (!isTestInstance()) logger.info('Updating live video views.', lTags()) + JobQueue.Instance.createJob({ + type: 'video-live-ending', + payload: { + videoId: fullVideo.id, - for (const videoId of this.watchersPerVideo.keys()) { - const notBefore = new Date().getTime() - VIEW_LIFETIME.LIVE + replayDirectory: live.saveReplay + ? await this.findReplayDirectory(fullVideo) + : undefined, - const watchers = this.watchersPerVideo.get(videoId) + liveSessionId: liveSession.id, + streamingPlaylistId: fullVideo.getHLSPlaylist()?.id, - const numWatchers = watchers.length + publishedAt: fullVideo.publishedAt.toISOString() + } + }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY }) - const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId) - video.views = numWatchers - await video.save() + fullVideo.state = live.permanentLive + ? VideoState.WAITING_FOR_LIVE + : VideoState.LIVE_ENDED - await federateVideoIfNeeded(video, false) - - PeerTubeSocket.Instance.sendVideoViewsUpdate(video) + await fullVideo.save() - // Only keep not expired watchers - const newWatchers = watchers.filter(w => w > notBefore) - this.watchersPerVideo.set(videoId, newWatchers) + PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo) - logger.debug('New live video views for %s is %d.', video.url, numWatchers, lTags()) + await federateVideoIfNeeded(fullVideo, false) + } catch (err) { + logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') }) } } @@ -380,31 +437,56 @@ class LiveManager { const videoUUIDs = await VideoModel.listPublishedLiveUUIDs() for (const uuid of videoUUIDs) { - await this.onAfterMuxingCleanup(uuid, true) + await this.onAfterMuxingCleanup({ videoId: uuid, cleanupNow: true }) } } + private async findReplayDirectory (video: MVideo) { + const directory = getLiveReplayBaseDirectory(video) + const files = await readdir(directory) + + if (files.length === 0) return undefined + + return join(directory, files.sort().reverse()[0]) + } + private buildAllResolutionsToTranscode (originResolution: number) { const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED - ? computeResolutionsToTranscode(originResolution, 'live') + ? computeLowerResolutionsToTranscode(originResolution, 'live') : [] return resolutionsEnabled.concat([ originResolution ]) } - private async createLivePlaylist (video: MVideo, allResolutions: number[]) { - const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid) - const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ - videoId: video.id, - playlistUrl, - segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive), - p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, allResolutions), - p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, + private async createLivePlaylist (video: MVideo, allResolutions: number[]): Promise { + const playlist = await VideoStreamingPlaylistModel.loadOrGenerate(video) + + playlist.playlistFilename = generateHLSMasterPlaylistFilename(true) + playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(true) + + playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION + playlist.type = VideoStreamingPlaylistType.HLS + + playlist.assignP2PMediaLoaderInfoHashes(video, allResolutions) + + return playlist.save() + } + + private saveStartingSession (videoLive: MVideoLiveVideo) { + const liveSession = new VideoLiveSessionModel({ + startDate: new Date(), + liveVideoId: videoLive.videoId + }) + + return liveSession.save() + } - type: VideoStreamingPlaylistType.HLS - }, { returning: true }) as [ MStreamingPlaylist, boolean ] + private async saveEndingSession (videoId: number, error: LiveVideoError | null) { + const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId) + liveSession.endDate = new Date() + liveSession.error = error - return Object.assign(videoStreamingPlaylist, { Video: video }) + return liveSession.save() } static get Instance () {