X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Flib%2Fjob-queue%2Fhandlers%2Fvideo-live-ending.ts;h=814f313a3bb8d946905bbbce3fb1ffba571e0d28;hb=a687879e94fa5d3ecdd76bec3d94d0e1698ee913;hp=599aabf80eacc5593969b3294131effcd5566e04;hpb=e4bf78561763cd84d22ebceb6f371cccf9a356d8;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/lib/job-queue/handlers/video-live-ending.ts b/server/lib/job-queue/handlers/video-live-ending.ts index 599aabf80..814f313a3 100644 --- a/server/lib/job-queue/handlers/video-live-ending.ts +++ b/server/lib/job-queue/handlers/video-live-ending.ts @@ -1,45 +1,73 @@ -import * as Bull from 'bull' +import { Job } from 'bullmq' import { readdir, remove } from 'fs-extra' import { join } from 'path' -import { getDurationFromVideoFile, getVideoFileResolution, hlsPlaylistToFragmentedMP4 } from '@server/helpers/ffmpeg-utils' -import { publishAndFederateIfNeeded } from '@server/lib/video' -import { getHLSDirectory } from '@server/lib/video-paths' -import { generateHlsPlaylist } from '@server/lib/video-transcoding' +import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' +import { federateVideoIfNeeded } from '@server/lib/activitypub/videos' +import { cleanupAndDestroyPermanentLive, cleanupTMPLiveFiles, cleanupUnsavedNormalLive } from '@server/lib/live' +import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveReplayBaseDirectory } from '@server/lib/paths' +import { generateVideoMiniature } from '@server/lib/thumbnail' +import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/hls-transcoding' +import { VideoPathManager } from '@server/lib/video-path-manager' +import { moveToNextState } from '@server/lib/video-state' import { VideoModel } from '@server/models/video/video' +import { VideoBlacklistModel } from '@server/models/video/video-blacklist' import { VideoFileModel } from '@server/models/video/video-file' import { VideoLiveModel } from '@server/models/video/video-live' +import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting' +import { VideoLiveSessionModel } from '@server/models/video/video-live-session' import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' -import { MStreamingPlaylist, MVideo, MVideoLive } from '@server/types/models' +import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models' +import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '@shared/ffmpeg' import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models' -import { logger } from '../../../helpers/logger' -import { generateVideoMiniature } from '@server/lib/thumbnail' +import { logger, loggerTagsFactory } from '../../../helpers/logger' + +const lTags = loggerTagsFactory('live', 'job') -async function processVideoLiveEnding (job: Bull.Job) { +async function processVideoLiveEnding (job: Job) { const payload = job.data as VideoLiveEndingPayload + logger.info('Processing video live ending for %s.', payload.videoId, { payload, ...lTags() }) + function logError () { - logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId) + logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId, lTags()) } const video = await VideoModel.load(payload.videoId) const live = await VideoLiveModel.loadByVideoId(payload.videoId) + const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId) - if (!video || !live) { + if (!video || !live || !liveSession) { logError() return } - const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) - if (!streamingPlaylist) { - logError() - return + const permanentLive = live.permanentLive + + liveSession.endingProcessed = true + await liveSession.save() + + if (liveSession.saveReplay !== true) { + return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId }) } - if (live.saveReplay !== true) { - return cleanupLive(video, streamingPlaylist) + if (permanentLive) { + await saveReplayToExternalVideo({ + liveVideo: video, + liveSession, + publishedAt: payload.publishedAt, + replayDirectory: payload.replayDirectory + }) + + return cleanupLiveAndFederate({ permanentLive, video, streamingPlaylistId: payload.streamingPlaylistId }) } - return saveLive(video, live) + return replaceLiveByReplay({ + video, + liveSession, + live, + permanentLive, + replayDirectory: payload.replayDirectory + }) } // --------------------------------------------------------------------------- @@ -50,108 +78,195 @@ export { // --------------------------------------------------------------------------- -async function saveLive (video: MVideo, live: MVideoLive) { - const hlsDirectory = getHLSDirectory(video, false) - const files = await readdir(hlsDirectory) - - const playlistFiles = files.filter(f => f.endsWith('.m3u8') && f !== 'master.m3u8') - const resolutions: number[] = [] - let duration: number - - for (const playlistFile of playlistFiles) { - const playlistPath = join(hlsDirectory, playlistFile) - const { videoFileResolution } = await getVideoFileResolution(playlistPath) +async function saveReplayToExternalVideo (options: { + liveVideo: MVideo + liveSession: MVideoLiveSession + publishedAt: string + replayDirectory: string +}) { + const { liveVideo, liveSession, publishedAt, replayDirectory } = options + + const replaySettings = await VideoLiveReplaySettingModel.load(liveSession.replaySettingId) + + const replayVideo = new VideoModel({ + name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`, + isLive: false, + state: VideoState.TO_TRANSCODE, + duration: 0, + + remote: liveVideo.remote, + category: liveVideo.category, + licence: liveVideo.licence, + language: liveVideo.language, + commentsEnabled: liveVideo.commentsEnabled, + downloadEnabled: liveVideo.downloadEnabled, + waitTranscoding: true, + nsfw: liveVideo.nsfw, + description: liveVideo.description, + support: liveVideo.support, + privacy: replaySettings.privacy, + channelId: liveVideo.channelId + }) as MVideoWithAllFiles + + replayVideo.Thumbnails = [] + replayVideo.VideoFiles = [] + replayVideo.VideoStreamingPlaylists = [] + + replayVideo.url = getLocalVideoActivityPubUrl(replayVideo) + + await replayVideo.save() + + liveSession.replayVideoId = replayVideo.id + await liveSession.save() + + // If live is blacklisted, also blacklist the replay + const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id) + if (blacklist) { + await VideoBlacklistModel.create({ + videoId: replayVideo.id, + unfederated: blacklist.unfederated, + reason: blacklist.reason, + type: blacklist.type + }) + } - const mp4TmpPath = buildMP4TmpPath(hlsDirectory, videoFileResolution) + await assignReplayFilesToVideo({ video: replayVideo, replayDirectory }) - // Playlist name is for example 3.m3u8 - // Segments names are 3-0.ts 3-1.ts etc - const shouldStartWith = playlistFile.replace(/\.m3u8$/, '') + '-' + await remove(replayDirectory) - const segmentFiles = files.filter(f => f.startsWith(shouldStartWith) && f.endsWith('.ts')) - await hlsPlaylistToFragmentedMP4(hlsDirectory, segmentFiles, mp4TmpPath) + for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) { + const image = await generateVideoMiniature({ video: replayVideo, videoFile: replayVideo.getMaxQualityFile(), type }) + await replayVideo.addAndSaveThumbnail(image) + } - if (!duration) { - duration = await getDurationFromVideoFile(mp4TmpPath) - } + await moveToNextState({ video: replayVideo, isNewVideo: true }) +} - resolutions.push(videoFileResolution) - } +async function replaceLiveByReplay (options: { + video: MVideo + liveSession: MVideoLiveSession + live: MVideoLive + permanentLive: boolean + replayDirectory: string +}) { + const { video, liveSession, live, permanentLive, replayDirectory } = options + + const replaySettings = await VideoLiveReplaySettingModel.load(liveSession.replaySettingId) + const videoWithFiles = await VideoModel.loadFull(video.id) + const hlsPlaylist = videoWithFiles.getHLSPlaylist() - await cleanupLiveFiles(hlsDirectory) + await cleanupTMPLiveFiles(videoWithFiles, hlsPlaylist) await live.destroy() - video.isLive = false - // Reinit views - video.views = 0 - video.state = VideoState.TO_TRANSCODE - video.duration = duration + videoWithFiles.isLive = false + videoWithFiles.privacy = replaySettings.privacy + videoWithFiles.waitTranscoding = true + videoWithFiles.state = VideoState.TO_TRANSCODE - await video.save() + await videoWithFiles.save() - // Remove old HLS playlist video files - const videoWithFiles = await VideoModel.loadWithFiles(video.id) + liveSession.replayVideoId = videoWithFiles.id + await liveSession.save() - const hlsPlaylist = videoWithFiles.getHLSPlaylist() await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id) + + // Reset playlist hlsPlaylist.VideoFiles = [] + hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename() + hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename() + await hlsPlaylist.save() - for (const resolution of resolutions) { - const videoInputPath = buildMP4TmpPath(hlsDirectory, resolution) - const { isPortraitMode } = await getVideoFileResolution(videoInputPath) + await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory }) - await generateHlsPlaylist({ - video: videoWithFiles, - videoInputPath, - resolution: resolution, - copyCodecs: true, - isPortraitMode - }) - - await remove(videoInputPath) + if (permanentLive) { // Remove session replay + await remove(replayDirectory) + } else { // We won't stream again in this live, we can delete the base replay directory + await remove(getLiveReplayBaseDirectory(videoWithFiles)) } // Regenerate the thumbnail & preview? if (videoWithFiles.getMiniature().automaticallyGenerated === true) { - await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.MINIATURE) + const miniature = await generateVideoMiniature({ + video: videoWithFiles, + videoFile: videoWithFiles.getMaxQualityFile(), + type: ThumbnailType.MINIATURE + }) + await videoWithFiles.addAndSaveThumbnail(miniature) } if (videoWithFiles.getPreview().automaticallyGenerated === true) { - await generateVideoMiniature(videoWithFiles, videoWithFiles.getMaxQualityFile(), ThumbnailType.PREVIEW) + const preview = await generateVideoMiniature({ + video: videoWithFiles, + videoFile: videoWithFiles.getMaxQualityFile(), + type: ThumbnailType.PREVIEW + }) + await videoWithFiles.addAndSaveThumbnail(preview) } - await publishAndFederateIfNeeded(video, true) + // We consider this is a new video + await moveToNextState({ video: videoWithFiles, isNewVideo: true }) } -async function cleanupLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) { - const hlsDirectory = getHLSDirectory(video) +async function assignReplayFilesToVideo (options: { + video: MVideo + replayDirectory: string +}) { + const { video, replayDirectory } = options + + const concatenatedTsFiles = await readdir(replayDirectory) + + for (const concatenatedTsFile of concatenatedTsFiles) { + const inputFileMutexReleaser = await VideoPathManager.Instance.lockFiles(video.uuid) + await video.reload() + + const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile) + + const probe = await ffprobePromise(concatenatedTsFilePath) + const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe) + const { resolution } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe) + const fps = await getVideoStreamFPS(concatenatedTsFilePath, probe) + + try { + await generateHlsPlaylistResolutionFromTS({ + video, + inputFileMutexReleaser, + concatenatedTsFilePath, + resolution, + fps, + isAAC: audioStream?.codec_name === 'aac' + }) + } catch (err) { + logger.error('Cannot generate HLS playlist resolution from TS files.', { err }) + } - await remove(hlsDirectory) + inputFileMutexReleaser() + } - streamingPlaylist.destroy() - .catch(err => logger.error('Cannot remove live streaming playlist.', { err })) + return video } -async function cleanupLiveFiles (hlsDirectory: string) { - const files = await readdir(hlsDirectory) - - for (const filename of files) { - if ( - filename.endsWith('.ts') || - filename.endsWith('.m3u8') || - filename.endsWith('.mpd') || - filename.endsWith('.m4s') || - filename.endsWith('.tmp') - ) { - const p = join(hlsDirectory, filename) - - remove(p) - .catch(err => logger.error('Cannot remove %s.', p, { err })) +async function cleanupLiveAndFederate (options: { + video: MVideo + permanentLive: boolean + streamingPlaylistId: number +}) { + const { permanentLive, video, streamingPlaylistId } = options + + const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId) + + if (streamingPlaylist) { + if (permanentLive) { + await cleanupAndDestroyPermanentLive(video, streamingPlaylist) + } else { + await cleanupUnsavedNormalLive(video, streamingPlaylist) } } -} -function buildMP4TmpPath (basePath: string, resolution: number) { - return join(basePath, resolution + '-tmp.mp4') + try { + const fullVideo = await VideoModel.loadFull(video.id) + return federateVideoIfNeeded(fullVideo, false, undefined) + } catch (err) { + logger.warn('Cannot federate live after cleanup', { videoId: video.id, err }) + } }