]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/live/live-manager.ts
Fix stucked HLS player
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-manager.ts
index 920d3a5ecb4fb54e0898407260afc760b124a820..649ad5195eb3d27a1b75b4e1b87ab9cd8c992048 100644 (file)
@@ -1,6 +1,7 @@
 
-import { readFile } from 'fs-extra'
+import { readdir, readFile } from 'fs-extra'
 import { createServer, Server } from 'net'
+import { join } from 'path'
 import { createServer as createServerTLS, Server as ServerTLS } from 'tls'
 import {
   computeLowerResolutionsToTranscode,
@@ -16,16 +17,17 @@ import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE } from '@server/initializers/
 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 { 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 } from '../paths'
+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/src/node_rtmp_session')
@@ -116,7 +118,7 @@ class LiveManager {
         logger.error('Cannot run RTMP server.', { err, ...lTags() })
       })
 
-      this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT)
+      this.rtmpServer.listen(CONFIG.LIVE.RTMP.PORT, CONFIG.LIVE.RTMP.HOSTNAME)
     }
 
     if (CONFIG.LIVE.RTMPS.ENABLED) {
@@ -139,7 +141,7 @@ class LiveManager {
         logger.error('Cannot run RTMPS server.', { err, ...lTags() })
       })
 
-      this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT)
+      this.rtmpsServer.listen(CONFIG.LIVE.RTMPS.PORT, CONFIG.LIVE.RTMPS.HOSTNAME)
     }
   }
 
@@ -172,10 +174,13 @@ 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)
   }
@@ -213,12 +218,12 @@ 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)
@@ -272,6 +277,8 @@ class LiveManager {
     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)
 
@@ -297,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 }))
     })
 
@@ -339,7 +351,7 @@ class LiveManager {
     const videoId = live.videoId
 
     try {
-      const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
+      const video = await VideoModel.loadFull(videoId)
 
       logger.info('Will publish and federate live %s.', video.url, localLTags)
 
@@ -349,48 +361,75 @@ class LiveManager {
 
       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)
 
-        PeerTubeSocket.Instance.sendVideoLiveNewState(video)
-      }, 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)
     } catch (err) {
       logger.error('Cannot save/federate live video %d.', videoId, { err, ...localLTags })
     }
   }
 
-  private onMuxingFFmpegEnd (videoId: number) {
+  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.loadFull(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.findLatestSessionOf(fullVideo.id)
+
+      // On server restart during a live
+      if (!liveSession.endDate) {
+        liveSession.endDate = new Date()
+        await liveSession.save()
       }
 
+      JobQueue.Instance.createJob({
+        type: 'video-live-ending',
+        payload: {
+          videoId: fullVideo.id,
+
+          replayDirectory: live.saveReplay
+            ? await this.findReplayDirectory(fullVideo)
+            : undefined,
+
+          liveSessionId: liveSession.id,
+          streamingPlaylistId: fullVideo.getHLSPlaylist()?.id,
+
+          publishedAt: fullVideo.publishedAt.toISOString()
+        }
+      }, { delay: cleanupNow ? 0 : VIDEO_LIVE.CLEANUP_DELAY })
+
+      fullVideo.state = live.permanentLive
+        ? VideoState.WAITING_FOR_LIVE
+        : VideoState.LIVE_ENDED
+
       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) })
+      logger.error('Cannot save/federate new video state of live streaming of video %d.', videoId, { err, ...lTags(videoId + '') })
     }
   }
 
@@ -398,10 +437,19 @@ 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
       ? computeLowerResolutionsToTranscode(originResolution, 'live')
@@ -424,6 +472,25 @@ class LiveManager {
     return playlist.save()
   }
 
+  private saveStartingSession (videoLive: MVideoLiveVideo) {
+    const liveSession = new VideoLiveSessionModel({
+      startDate: new Date(),
+      liveVideoId: videoLive.videoId
+    })
+
+    return liveSession.save()
+  }
+
+  private async saveEndingSession (videoId: number, error: LiveVideoError | null) {
+    const liveSession = await VideoLiveSessionModel.findCurrentSessionOf(videoId)
+    if (!liveSession) return
+
+    liveSession.endDate = new Date()
+    liveSession.error = error
+
+    return liveSession.save()
+  }
+
   static get Instance () {
     return this.instance || (this.instance = new this())
   }