]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live-manager.ts
Add watch messages if live has not started
[github/Chocobozzz/PeerTube.git] / server / lib / live-manager.ts
1
2 import { AsyncQueue, queue } from 'async'
3 import * as chokidar from 'chokidar'
4 import { FfmpegCommand } from 'fluent-ffmpeg'
5 import { ensureDir } from 'fs-extra'
6 import { basename } from 'path'
7 import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
8 import { logger } from '@server/helpers/logger'
9 import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
10 import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11 import { VideoModel } from '@server/models/video/video'
12 import { VideoFileModel } from '@server/models/video/video-file'
13 import { VideoLiveModel } from '@server/models/video/video-live'
14 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
15 import { MStreamingPlaylist, MVideoLiveVideo } from '@server/types/models'
16 import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
17 import { federateVideoIfNeeded } from './activitypub/videos'
18 import { buildSha256Segment } from './hls'
19 import { JobQueue } from './job-queue'
20 import { PeerTubeSocket } from './peertube-socket'
21 import { getHLSDirectory } from './video-paths'
22
23 const NodeRtmpServer = require('node-media-server/node_rtmp_server')
24 const context = require('node-media-server/node_core_ctx')
25 const nodeMediaServerLogger = require('node-media-server/node_core_logger')
26
27 // Disable node media server logs
28 nodeMediaServerLogger.setLogType(0)
29
30 const config = {
31 rtmp: {
32 port: CONFIG.LIVE.RTMP.PORT,
33 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
34 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
35 ping: VIDEO_LIVE.RTMP.PING,
36 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
37 },
38 transcoding: {
39 ffmpeg: 'ffmpeg'
40 }
41 }
42
43 type SegmentSha256QueueParam = {
44 operation: 'update' | 'delete'
45 videoUUID: string
46 segmentPath: string
47 }
48
49 class LiveManager {
50
51 private static instance: LiveManager
52
53 private readonly transSessions = new Map<string, FfmpegCommand>()
54 private readonly videoSessions = new Map<number, string>()
55 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
56
57 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
58 private rtmpServer: any
59
60 private constructor () {
61 }
62
63 init () {
64 const events = this.getContext().nodeEvent
65 events.on('postPublish', (sessionId: string, streamPath: string) => {
66 logger.debug('RTMP received stream', { id: sessionId, streamPath })
67
68 const splittedPath = streamPath.split('/')
69 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
70 logger.warn('Live path is incorrect.', { streamPath })
71 return this.abortSession(sessionId)
72 }
73
74 this.handleSession(sessionId, streamPath, splittedPath[2])
75 .catch(err => logger.error('Cannot handle sessions.', { err }))
76 })
77
78 events.on('donePublish', sessionId => {
79 this.abortSession(sessionId)
80 })
81
82 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
83 const promise = options.operation === 'update'
84 ? this.addSegmentSha(options)
85 : Promise.resolve(this.removeSegmentSha(options))
86
87 promise.then(() => cb())
88 .catch(err => {
89 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
90 cb()
91 })
92 })
93
94 registerConfigChangedHandler(() => {
95 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
96 this.run()
97 return
98 }
99
100 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
101 this.stop()
102 }
103 })
104 }
105
106 run () {
107 logger.info('Running RTMP server.')
108
109 this.rtmpServer = new NodeRtmpServer(config)
110 this.rtmpServer.run()
111 }
112
113 stop () {
114 logger.info('Stopping RTMP server.')
115
116 this.rtmpServer.stop()
117 this.rtmpServer = undefined
118 }
119
120 getSegmentsSha256 (videoUUID: string) {
121 return this.segmentsSha256.get(videoUUID)
122 }
123
124 stopSessionOf (videoId: number) {
125 const sessionId = this.videoSessions.get(videoId)
126 if (!sessionId) return
127
128 this.abortSession(sessionId)
129
130 this.onEndTransmuxing(videoId)
131 .catch(err => logger.error('Cannot end transmuxing of video %d.', videoId, { err }))
132 }
133
134 private getContext () {
135 return context
136 }
137
138 private abortSession (id: string) {
139 const session = this.getContext().sessions.get(id)
140 if (session) session.stop()
141
142 const transSession = this.transSessions.get(id)
143 if (transSession) transSession.kill('SIGKILL')
144 }
145
146 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
147 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
148 if (!videoLive) {
149 logger.warn('Unknown live video with stream key %s.', streamKey)
150 return this.abortSession(sessionId)
151 }
152
153 const video = videoLive.Video
154 if (video.isBlacklisted()) {
155 logger.warn('Video is blacklisted. Refusing stream %s.', streamKey)
156 return this.abortSession(sessionId)
157 }
158
159 this.videoSessions.set(video.id, sessionId)
160
161 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
162
163 const session = this.getContext().sessions.get(sessionId)
164 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
165 ? computeResolutionsToTranscode(session.videoHeight, 'live')
166 : []
167
168 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
169
170 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
171 videoId: video.id,
172 playlistUrl,
173 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
174 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
175 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
176
177 type: VideoStreamingPlaylistType.HLS
178 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
179
180 return this.runMuxing({
181 sessionId,
182 videoLive,
183 playlist: videoStreamingPlaylist,
184 streamPath,
185 originalResolution: session.videoHeight,
186 resolutionsEnabled
187 })
188 }
189
190 private async runMuxing (options: {
191 sessionId: string
192 videoLive: MVideoLiveVideo
193 playlist: MStreamingPlaylist
194 streamPath: string
195 resolutionsEnabled: number[]
196 originalResolution: number
197 }) {
198 const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options
199 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
200
201 for (let i = 0; i < allResolutions.length; i++) {
202 const resolution = allResolutions[i]
203
204 VideoFileModel.upsert({
205 resolution,
206 size: -1,
207 extname: '.ts',
208 infoHash: null,
209 fps: -1,
210 videoStreamingPlaylistId: playlist.id
211 }).catch(err => {
212 logger.error('Cannot create file for live streaming.', { err })
213 })
214 }
215
216 const outPath = getHLSDirectory(videoLive.Video)
217 await ensureDir(outPath)
218
219 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
220 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
221 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions)
222 : runLiveMuxing(rtmpUrl, outPath)
223
224 logger.info('Running live muxing/transcoding.')
225
226 this.transSessions.set(sessionId, ffmpegExec)
227
228 const videoUUID = videoLive.Video.uuid
229 const tsWatcher = chokidar.watch(outPath + '/*.ts')
230
231 const updateHandler = segmentPath => {
232 this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
233 }
234
235 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
236
237 tsWatcher.on('add', p => updateHandler(p))
238 tsWatcher.on('change', p => updateHandler(p))
239 tsWatcher.on('unlink', p => deleteHandler(p))
240
241 const masterWatcher = chokidar.watch(outPath + '/master.m3u8')
242 masterWatcher.on('add', async () => {
243 try {
244 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoLive.videoId)
245
246 video.state = VideoState.PUBLISHED
247 await video.save()
248 videoLive.Video = video
249
250 await federateVideoIfNeeded(video, false)
251
252 PeerTubeSocket.Instance.sendVideoLiveNewState(video)
253 } catch (err) {
254 logger.error('Cannot federate video %d.', videoLive.videoId, { err })
255 } finally {
256 masterWatcher.close()
257 .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err }))
258 }
259 })
260
261 const onFFmpegEnded = () => {
262 logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', streamPath)
263
264 Promise.all([ tsWatcher.close(), masterWatcher.close() ])
265 .catch(err => logger.error('Cannot close watchers of %s.', outPath, { err }))
266
267 this.onEndTransmuxing(videoLive.Video.id)
268 .catch(err => logger.error('Error in closed transmuxing.', { err }))
269 }
270
271 ffmpegExec.on('error', (err, stdout, stderr) => {
272 onFFmpegEnded()
273
274 // Don't care that we killed the ffmpeg process
275 if (err?.message?.includes('SIGKILL')) return
276
277 logger.error('Live transcoding error.', { err, stdout, stderr })
278 })
279
280 ffmpegExec.on('end', () => onFFmpegEnded())
281 }
282
283 private async onEndTransmuxing (videoId: number) {
284 try {
285 const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
286 if (!fullVideo) return
287
288 JobQueue.Instance.createJob({
289 type: 'video-live-ending',
290 payload: {
291 videoId: fullVideo.id
292 }
293 }, { delay: VIDEO_LIVE.CLEANUP_DELAY })
294
295 // FIXME: use end
296 fullVideo.state = VideoState.WAITING_FOR_LIVE
297 await fullVideo.save()
298
299 PeerTubeSocket.Instance.sendVideoLiveNewState(fullVideo)
300
301 await federateVideoIfNeeded(fullVideo, false)
302 } catch (err) {
303 logger.error('Cannot save/federate new video state of live streaming.', { err })
304 }
305 }
306
307 private async addSegmentSha (options: SegmentSha256QueueParam) {
308 const segmentName = basename(options.segmentPath)
309 logger.debug('Updating live sha segment %s.', options.segmentPath)
310
311 const shaResult = await buildSha256Segment(options.segmentPath)
312
313 if (!this.segmentsSha256.has(options.videoUUID)) {
314 this.segmentsSha256.set(options.videoUUID, new Map())
315 }
316
317 const filesMap = this.segmentsSha256.get(options.videoUUID)
318 filesMap.set(segmentName, shaResult)
319 }
320
321 private removeSegmentSha (options: SegmentSha256QueueParam) {
322 const segmentName = basename(options.segmentPath)
323
324 logger.debug('Removing live sha segment %s.', options.segmentPath)
325
326 const filesMap = this.segmentsSha256.get(options.videoUUID)
327 if (!filesMap) {
328 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
329 return
330 }
331
332 if (!filesMap.has(segmentName)) {
333 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
334 return
335 }
336
337 filesMap.delete(segmentName)
338 }
339
340 static get Instance () {
341 return this.instance || (this.instance = new this())
342 }
343 }
344
345 // ---------------------------------------------------------------------------
346
347 export {
348 LiveManager
349 }