]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/live/shared/muxing-session.ts
Typo
[github/Chocobozzz/PeerTube.git] / server / lib / live / shared / muxing-session.ts
index 7788eea2d29f5319efbc15d0a5d73f72e05dabf1..588ee874989055685c26b561a6a91e18c4b80818 100644 (file)
@@ -1,19 +1,19 @@
 
-import * as Bluebird from 'bluebird'
-import * as chokidar from 'chokidar'
+import { mapSeries } from 'bluebird'
+import { FSWatcher, watch } from 'chokidar'
 import { FfmpegCommand } from 'fluent-ffmpeg'
 import { appendFile, ensureDir, readFile, stat } from 'fs-extra'
 import { basename, join } from 'path'
 import { EventEmitter } from 'stream'
-import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg-utils'
+import { getLiveMuxingCommand, getLiveTranscodingCommand } from '@server/helpers/ffmpeg'
 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
 import { CONFIG } from '@server/initializers/config'
 import { MEMOIZE_TTL, VIDEO_LIVE } from '@server/initializers/constants'
 import { VideoFileModel } from '@server/models/video/video-file'
 import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models'
-import { VideoTranscodingProfilesManager } from '../../transcoding/video-transcoding-profiles'
+import { getLiveDirectory, getLiveReplayBaseDirectory } from '../../paths'
+import { VideoTranscodingProfilesManager } from '../../transcoding/default-transcoding-profiles'
 import { isAbleToUploadVideo } from '../../user'
-import { getHLSDirectory } from '../../video-paths'
 import { LiveQuotaStore } from '../live-quota-store'
 import { LiveSegmentShaStore } from '../live-segment-sha-store'
 import { buildConcatenatedName } from '../live-utils'
@@ -52,22 +52,26 @@ class MuxingSession extends EventEmitter {
   private readonly sessionId: string
   private readonly videoLive: MVideoLiveVideo
   private readonly streamingPlaylist: MStreamingPlaylistVideo
-  private readonly rtmpUrl: string
+  private readonly inputUrl: string
   private readonly fps: number
   private readonly allResolutions: number[]
 
+  private readonly bitrate: number
+  private readonly ratio: number
+
   private readonly videoId: number
   private readonly videoUUID: string
   private readonly saveReplay: boolean
 
-  private toto: Buffer
+  private readonly outDirectory: string
+  private readonly replayDirectory: string
 
   private readonly lTags: LoggerTagsFn
 
   private segmentsToProcessPerPlaylist: { [playlistId: string]: string[] } = {}
 
-  private tsWatcher: chokidar.FSWatcher
-  private masterWatcher: chokidar.FSWatcher
+  private tsWatcher: FSWatcher
+  private masterWatcher: FSWatcher
 
   private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {
     return isAbleToUploadVideo(userId, 1000)
@@ -83,8 +87,10 @@ class MuxingSession extends EventEmitter {
     sessionId: string
     videoLive: MVideoLiveVideo
     streamingPlaylist: MStreamingPlaylistVideo
-    rtmpUrl: string
+    inputUrl: string
     fps: number
+    bitrate: number
+    ratio: number
     allResolutions: number[]
   }) {
     super()
@@ -94,8 +100,12 @@ class MuxingSession extends EventEmitter {
     this.sessionId = options.sessionId
     this.videoLive = options.videoLive
     this.streamingPlaylist = options.streamingPlaylist
-    this.rtmpUrl = options.rtmpUrl
+    this.inputUrl = options.inputUrl
     this.fps = options.fps
+
+    this.bitrate = options.bitrate
+    this.ratio = options.ratio
+
     this.allResolutions = options.allResolutions
 
     this.videoId = this.videoLive.Video.id
@@ -103,37 +113,58 @@ class MuxingSession extends EventEmitter {
 
     this.saveReplay = this.videoLive.saveReplay
 
-    this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
+    this.outDirectory = getLiveDirectory(this.videoLive.Video)
+    this.replayDirectory = join(getLiveReplayBaseDirectory(this.videoLive.Video), new Date().toISOString())
 
-    this.toto = Buffer.alloc(1_000_000_000)
+    this.lTags = loggerTagsFactory('live', this.sessionId, this.videoUUID)
   }
 
   async runMuxing () {
     this.createFiles()
 
-    const outPath = await this.prepareDirectories()
+    await this.prepareDirectories()
 
     this.ffmpegCommand = CONFIG.LIVE.TRANSCODING.ENABLED
       ? await getLiveTranscodingCommand({
-        rtmpUrl: this.rtmpUrl,
-        outPath,
+        inputUrl: this.inputUrl,
+
+        outPath: this.outDirectory,
+        masterPlaylistName: this.streamingPlaylist.playlistFilename,
+
+        latencyMode: this.videoLive.latencyMode,
+
         resolutions: this.allResolutions,
         fps: this.fps,
+        bitrate: this.bitrate,
+        ratio: this.ratio,
+
         availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(),
         profile: CONFIG.LIVE.TRANSCODING.PROFILE
       })
-      : getLiveMuxingCommand(this.rtmpUrl, outPath)
+      : getLiveMuxingCommand({
+        inputUrl: this.inputUrl,
+        outPath: this.outDirectory,
+        masterPlaylistName: this.streamingPlaylist.playlistFilename,
+        latencyMode: this.videoLive.latencyMode
+      })
+
+    logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags())
 
-    logger.info('Running live muxing/transcoding for %s.', this.videoUUID, this.lTags)
+    this.watchTSFiles(this.outDirectory)
+    this.watchMasterFile(this.outDirectory)
 
-    this.watchTSFiles(outPath)
-    this.watchMasterFile(outPath)
+    let ffmpegShellCommand: string
+    this.ffmpegCommand.on('start', cmdline => {
+      ffmpegShellCommand = cmdline
+
+      logger.debug('Running ffmpeg command for live', { ffmpegShellCommand, ...this.lTags() })
+    })
 
     this.ffmpegCommand.on('error', (err, stdout, stderr) => {
-      this.onFFmpegError(err, stdout, stderr, outPath)
+      this.onFFmpegError({ err, stdout, stderr, outPath: this.outDirectory, ffmpegShellCommand })
     })
 
-    this.ffmpegCommand.on('end', () => this.onFFmpegEnded(outPath))
+    this.ffmpegCommand.on('end', () => this.onFFmpegEnded(this.outDirectory))
 
     this.ffmpegCommand.run()
   }
@@ -150,19 +181,27 @@ class MuxingSession extends EventEmitter {
     this.hasClientSocketInBadHealthWithCache.clear()
   }
 
-  private onFFmpegError (err: any, stdout: string, stderr: string, outPath: string) {
+  private onFFmpegError (options: {
+    err: any
+    stdout: string
+    stderr: string
+    outPath: string
+    ffmpegShellCommand: string
+  }) {
+    const { err, stdout, stderr, outPath, ffmpegShellCommand } = options
+
     this.onFFmpegEnded(outPath)
 
     // Don't care that we killed the ffmpeg process
     if (err?.message?.includes('Exiting normally')) return
 
-    logger.error('Live transcoding error.', { err, stdout, stderr, ...this.lTags })
+    logger.error('Live transcoding error.', { err, stdout, stderr, ffmpegShellCommand, ...this.lTags() })
 
     this.emit('ffmpeg-error', ({ sessionId: this.sessionId }))
   }
 
   private onFFmpegEnded (outPath: string) {
-    logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.rtmpUrl, this.lTags)
+    logger.info('RTMP transmuxing for video %s ended. Scheduling cleanup', this.inputUrl, this.lTags())
 
     setTimeout(() => {
       // Wait latest segments generation, and close watchers
@@ -177,7 +216,7 @@ class MuxingSession extends EventEmitter {
         .catch(err => {
           logger.error(
             'Cannot close watchers of %s or process remaining hash segments.', outPath,
-            { err, ...this.lTags }
+            { err, ...this.lTags() }
           )
         })
 
@@ -186,25 +225,25 @@ class MuxingSession extends EventEmitter {
   }
 
   private watchMasterFile (outPath: string) {
-    this.masterWatcher = chokidar.watch(outPath + '/master.m3u8')
+    this.masterWatcher = watch(outPath + '/' + this.streamingPlaylist.playlistFilename)
 
-    this.masterWatcher.on('add', async () => {
+    this.masterWatcher.on('add', () => {
       this.emit('master-playlist-created', { videoId: this.videoId })
 
       this.masterWatcher.close()
-        .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags }))
+        .catch(err => logger.error('Cannot close master watcher of %s.', outPath, { err, ...this.lTags() }))
     })
   }
 
   private watchTSFiles (outPath: string) {
     const startStreamDateTime = new Date().getTime()
 
-    this.tsWatcher = chokidar.watch(outPath + '/*.ts')
+    this.tsWatcher = watch(outPath + '/*.ts')
 
     const playlistIdMatcher = /^([\d+])-/
 
-    const addHandler = async segmentPath => {
-      logger.debug('Live add handler of %s.', segmentPath, this.lTags)
+    const addHandler = async (segmentPath: string) => {
+      logger.debug('Live add handler of %s.', segmentPath, this.lTags())
 
       const playlistId = basename(segmentPath).match(playlistIdMatcher)[0]
 
@@ -248,7 +287,7 @@ class MuxingSession extends EventEmitter {
 
       return canUpload !== true
     } catch (err) {
-      logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags })
+      logger.error('Cannot stat %s or check quota of %d.', segmentPath, this.user.id, { err, ...this.lTags() })
     }
   }
 
@@ -266,21 +305,16 @@ class MuxingSession extends EventEmitter {
       })
 
       VideoFileModel.customUpsert(file, 'streaming-playlist', null)
-        .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags }))
+        .catch(err => logger.error('Cannot create file for live streaming.', { err, ...this.lTags() }))
     }
   }
 
   private async prepareDirectories () {
-    const outPath = getHLSDirectory(this.videoLive.Video)
-    await ensureDir(outPath)
-
-    const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY)
+    await ensureDir(this.outDirectory)
 
     if (this.videoLive.saveReplay === true) {
-      await ensureDir(replayDirectory)
+      await ensureDir(this.replayDirectory)
     }
-
-    return outPath
   }
 
   private isDurationConstraintValid (streamingStartTime: number) {
@@ -295,21 +329,21 @@ class MuxingSession extends EventEmitter {
   }
 
   private processSegments (hlsVideoPath: string, segmentPaths: string[]) {
-    Bluebird.mapSeries(segmentPaths, async previousSegment => {
+    mapSeries(segmentPaths, async previousSegment => {
       // Add sha hash of previous segments, because ffmpeg should have finished generating them
       await LiveSegmentShaStore.Instance.addSegmentSha(this.videoUUID, previousSegment)
 
       if (this.saveReplay) {
         await this.addSegmentToReplay(hlsVideoPath, previousSegment)
       }
-    }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags }))
+    }).catch(err => logger.error('Cannot process segments in %s', hlsVideoPath, { err, ...this.lTags() }))
   }
 
   private hasClientSocketInBadHealth (sessionId: string) {
     const rtmpSession = this.context.sessions.get(sessionId)
 
     if (!rtmpSession) {
-      logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags)
+      logger.warn('Cannot get session %s to check players socket health.', sessionId, this.lTags())
       return
     }
 
@@ -317,7 +351,7 @@ class MuxingSession extends EventEmitter {
       const playerSession = this.context.sessions.get(playerSessionId)
 
       if (!playerSession) {
-        logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags)
+        logger.error('Cannot get player session %s to check socket health.', playerSession, this.lTags())
         continue
       }
 
@@ -331,14 +365,14 @@ class MuxingSession extends EventEmitter {
 
   private async addSegmentToReplay (hlsVideoPath: string, segmentPath: string) {
     const segmentName = basename(segmentPath)
-    const dest = join(hlsVideoPath, VIDEO_LIVE.REPLAY_DIRECTORY, buildConcatenatedName(segmentName))
+    const dest = join(this.replayDirectory, buildConcatenatedName(segmentName))
 
     try {
       const data = await readFile(segmentPath)
 
       await appendFile(dest, data)
     } catch (err) {
-      logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags })
+      logger.error('Cannot copy segment %s to replay directory.', segmentPath, { err, ...this.lTags() })
     }
   }
 }