X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Flib%2Fjob-queue%2Fhandlers%2Fvideo-live-ending.ts;h=55fd09344135bf4a2b5a7e0a7e8af8472c887898;hb=26e3e98ff0e222a9fb9226938ac6902af77921bd;hp=cd5bb1d1cdbbf864470802d105d4546b6cce050d;hpb=31c82cd914e13dbf53280d0aad0740d70c414441;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 cd5bb1d1c..55fd09344 100644 --- a/server/lib/job-queue/handlers/video-live-ending.ts +++ b/server/lib/job-queue/handlers/video-live-ending.ts @@ -1,33 +1,60 @@ -import * as Bull from 'bull' -import { readdir, remove } from 'fs-extra' +import { Job } from 'bull' +import { pathExists, readdir, remove } from 'fs-extra' import { join } from 'path' -import { getVideoFileResolution, hlsPlaylistToFragmentedMP4 } from '@server/helpers/ffmpeg-utils' -import { getHLSDirectory } from '@server/lib/video-paths' -import { generateHlsPlaylist } from '@server/lib/video-transcoding' +import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamDuration } from '@server/helpers/ffmpeg' +import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' +import { federateVideoIfNeeded } from '@server/lib/activitypub/videos' +import { cleanupLive, LiveSegmentShaStore } from '@server/lib/live' +import { + generateHLSMasterPlaylistFilename, + generateHlsSha256SegmentsFilename, + getLiveDirectory, + getLiveReplayBaseDirectory +} from '@server/lib/paths' +import { generateVideoMiniature } from '@server/lib/thumbnail' +import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/transcoding' +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 { 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 { VideoLiveEndingPayload, VideoState } from '@shared/models' +import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models' +import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@shared/models' import { logger } from '../../../helpers/logger' -async function processVideoLiveEnding (job: Bull.Job) { +async function processVideoLiveEnding (job: Job) { const payload = job.data as VideoLiveEndingPayload - const video = await VideoModel.load(payload.videoId) - const live = await VideoLiveModel.loadByVideoId(payload.videoId) + logger.info('Processing video live ending for %s.', payload.videoId, { payload }) - const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id) - if (!video || !streamingPlaylist || !live) { + function logError () { logger.warn('Video live %d does not exist anymore. Cannot process live ending.', payload.videoId) + } + + const liveVideo = await VideoModel.load(payload.videoId) + const live = await VideoLiveModel.loadByVideoId(payload.videoId) + const liveSession = await VideoLiveSessionModel.load(payload.liveSessionId) + + if (!liveVideo || !live || !liveSession) { + logError() return } + LiveSegmentShaStore.Instance.cleanupShaSegments(liveVideo.uuid) + if (live.saveReplay !== true) { - return cleanupLive(video, streamingPlaylist) + return cleanupLiveAndFederate({ liveVideo }) } - return saveLive(video, live) + if (live.permanentLive) { + await saveReplayToExternalVideo({ liveVideo, liveSession, publishedAt: payload.publishedAt, replayDirectory: payload.replayDirectory }) + + return cleanupLiveAndFederate({ liveVideo }) + } + + return replaceLiveByReplay({ liveVideo, live, liveSession, replayDirectory: payload.replayDirectory }) } // --------------------------------------------------------------------------- @@ -38,66 +65,182 @@ export { // --------------------------------------------------------------------------- -async function saveLive (video: MVideo, live: MVideoLive) { - const hlsDirectory = getHLSDirectory(video, false) - const files = await readdir(hlsDirectory) +async function saveReplayToExternalVideo (options: { + liveVideo: MVideo + liveSession: MVideoLiveSession + publishedAt: string + replayDirectory: string +}) { + const { liveVideo, liveSession, publishedAt, replayDirectory } = options - const playlistFiles = files.filter(f => f.endsWith('.m3u8') && f !== 'master.m3u8') - const resolutions: number[] = [] + await cleanupTMPLiveFiles(getLiveDirectory(liveVideo)) - for (const playlistFile of playlistFiles) { - const playlistPath = join(hlsDirectory, playlistFile) - const { videoFileResolution } = await getVideoFileResolution(playlistPath) + const video = new VideoModel({ + name: `${liveVideo.name} - ${new Date(publishedAt).toLocaleString()}`, + isLive: false, + state: VideoState.TO_TRANSCODE, + duration: 0, - const mp4TmpName = buildMP4TmpName(videoFileResolution) + 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: liveVideo.privacy, + channelId: liveVideo.channelId + }) as MVideoWithAllFiles - // Playlist name is for example 3.m3u8 - // Segments names are 3-0.ts 3-1.ts etc - const shouldStartWith = playlistFile.replace(/\.m3u8$/, '') + '-' + video.Thumbnails = [] + video.VideoFiles = [] + video.VideoStreamingPlaylists = [] + + video.url = getLocalVideoActivityPubUrl(video) + + await video.save() - const segmentFiles = files.filter(f => f.startsWith(shouldStartWith) && f.endsWith('.ts')) - await hlsPlaylistToFragmentedMP4(hlsDirectory, segmentFiles, mp4TmpName) + liveSession.replayVideoId = video.id + await liveSession.save() - resolutions.push(videoFileResolution) + // If live is blacklisted, also blacklist the replay + const blacklist = await VideoBlacklistModel.loadByVideoId(liveVideo.id) + if (blacklist) { + await VideoBlacklistModel.create({ + videoId: video.id, + unfederated: blacklist.unfederated, + reason: blacklist.reason, + type: blacklist.type + }) + } + + await assignReplayFilesToVideo({ video, replayDirectory }) + + await remove(replayDirectory) + + for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) { + const image = await generateVideoMiniature({ video, videoFile: video.getMaxQualityFile(), type }) + await video.addAndSaveThumbnail(image) } - await cleanupLiveFiles(hlsDirectory) + await moveToNextState({ video, isNewVideo: true }) +} + +async function replaceLiveByReplay (options: { + liveVideo: MVideo + liveSession: MVideoLiveSession + live: MVideoLive + replayDirectory: string +}) { + const { liveVideo, liveSession, live, replayDirectory } = options + + await cleanupTMPLiveFiles(getLiveDirectory(liveVideo)) await live.destroy() - video.isLive = false - video.state = VideoState.TO_TRANSCODE - await video.save() + liveVideo.isLive = false + liveVideo.waitTranscoding = true + liveVideo.state = VideoState.TO_TRANSCODE + + await liveVideo.save() + + liveSession.replayVideoId = liveVideo.id + await liveSession.save() + + // Remove old HLS playlist video files + const videoWithFiles = await VideoModel.loadAndPopulateAccountAndServerAndTags(liveVideo.id) - const videoWithFiles = await VideoModel.loadWithFiles(video.id) + const hlsPlaylist = videoWithFiles.getHLSPlaylist() + await VideoFileModel.removeHLSFilesOfVideoId(hlsPlaylist.id) - for (const resolution of resolutions) { - const videoInputPath = buildMP4TmpName(resolution) - const { isPortraitMode } = await getVideoFileResolution(videoInputPath) + // Reset playlist + hlsPlaylist.VideoFiles = [] + hlsPlaylist.playlistFilename = generateHLSMasterPlaylistFilename() + hlsPlaylist.segmentsSha256Filename = generateHlsSha256SegmentsFilename() + await hlsPlaylist.save() - await generateHlsPlaylist({ + await assignReplayFilesToVideo({ video: videoWithFiles, replayDirectory }) + + await remove(getLiveReplayBaseDirectory(videoWithFiles)) + + // Regenerate the thumbnail & preview? + if (videoWithFiles.getMiniature().automaticallyGenerated === true) { + const miniature = await generateVideoMiniature({ video: videoWithFiles, - videoInputPath, - resolution: resolution, - copyCodecs: true, - isPortraitMode + videoFile: videoWithFiles.getMaxQualityFile(), + type: ThumbnailType.MINIATURE }) + await videoWithFiles.addAndSaveThumbnail(miniature) } - video.state = VideoState.PUBLISHED - await video.save() + if (videoWithFiles.getPreview().automaticallyGenerated === true) { + const preview = await generateVideoMiniature({ + video: videoWithFiles, + videoFile: videoWithFiles.getMaxQualityFile(), + type: ThumbnailType.PREVIEW + }) + await videoWithFiles.addAndSaveThumbnail(preview) + } + + // We consider this is a new video + await moveToNextState({ video: videoWithFiles, isNewVideo: true }) +} + +async function assignReplayFilesToVideo (options: { + video: MVideo + replayDirectory: string +}) { + const { video, replayDirectory } = options + + let durationDone = false + + const concatenatedTsFiles = await readdir(replayDirectory) + + for (const concatenatedTsFile of concatenatedTsFiles) { + const concatenatedTsFilePath = join(replayDirectory, concatenatedTsFile) + + const probe = await ffprobePromise(concatenatedTsFilePath) + const { audioStream } = await getAudioStream(concatenatedTsFilePath, probe) + + const { resolution, isPortraitMode } = await getVideoStreamDimensionsInfo(concatenatedTsFilePath, probe) + + const { resolutionPlaylistPath: outputPath } = await generateHlsPlaylistResolutionFromTS({ + video, + concatenatedTsFilePath, + resolution, + isPortraitMode, + isAAC: audioStream?.codec_name === 'aac' + }) + + if (!durationDone) { + video.duration = await getVideoStreamDuration(outputPath) + await video.save() + + durationDone = true + } + } + + return video } -async function cleanupLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) { - const hlsDirectory = getHLSDirectory(video, false) +async function cleanupLiveAndFederate (options: { + liveVideo: MVideo +}) { + const { liveVideo } = options - await cleanupLiveFiles(hlsDirectory) + const streamingPlaylist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(liveVideo.id) + await cleanupLive(liveVideo, streamingPlaylist) - streamingPlaylist.destroy() - .catch(err => logger.error('Cannot remove live streaming playlist.', { err })) + const fullVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(liveVideo.id) + return federateVideoIfNeeded(fullVideo, false, undefined) } -async function cleanupLiveFiles (hlsDirectory: string) { +async function cleanupTMPLiveFiles (hlsDirectory: string) { + if (!await pathExists(hlsDirectory)) return + const files = await readdir(hlsDirectory) for (const filename of files) { @@ -115,7 +258,3 @@ async function cleanupLiveFiles (hlsDirectory: string) { } } } - -function buildMP4TmpName (resolution: number) { - return resolution + '-tmp.mp4' -}