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