aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2020-09-17 09:20:52 +0200
committerChocobozzz <chocobozzz@cpy.re>2020-11-09 15:33:04 +0100
commitc6c0fa6cd8fe8f752463d8982c3dbcd448739c4e (patch)
tree79304b0152b0a38d33b26e65d4acdad0da4032a7 /server/lib
parent110d463fece85e87a26aca48a6048ae0017a27b3 (diff)
downloadPeerTube-c6c0fa6cd8fe8f752463d8982c3dbcd448739c4e.tar.gz
PeerTube-c6c0fa6cd8fe8f752463d8982c3dbcd448739c4e.tar.zst
PeerTube-c6c0fa6cd8fe8f752463d8982c3dbcd448739c4e.zip
Live streaming implementation first step
Diffstat (limited to 'server/lib')
-rw-r--r--server/lib/hls.ts10
-rw-r--r--server/lib/job-queue/handlers/video-transcoding.ts2
-rw-r--r--server/lib/live-manager.ts310
-rw-r--r--server/lib/video-paths.ts3
-rw-r--r--server/lib/video-transcoding.ts7
-rw-r--r--server/lib/video.ts31
6 files changed, 356 insertions, 7 deletions
diff --git a/server/lib/hls.ts b/server/lib/hls.ts
index 76380b1f2..e38a8788c 100644
--- a/server/lib/hls.ts
+++ b/server/lib/hls.ts
@@ -65,7 +65,7 @@ async function updateMasterHLSPlaylist (video: MVideoWithFile) {
65 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n') 65 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
66} 66}
67 67
68async function updateSha256Segments (video: MVideoWithFile) { 68async function updateSha256VODSegments (video: MVideoWithFile) {
69 const json: { [filename: string]: { [range: string]: string } } = {} 69 const json: { [filename: string]: { [range: string]: string } } = {}
70 70
71 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) 71 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
@@ -101,6 +101,11 @@ async function updateSha256Segments (video: MVideoWithFile) {
101 await outputJSON(outputPath, json) 101 await outputJSON(outputPath, json)
102} 102}
103 103
104async function buildSha256Segment (segmentPath: string) {
105 const buf = await readFile(segmentPath)
106 return sha256(buf)
107}
108
104function getRangesFromPlaylist (playlistContent: string) { 109function getRangesFromPlaylist (playlistContent: string) {
105 const ranges: { offset: number, length: number }[] = [] 110 const ranges: { offset: number, length: number }[] = []
106 const lines = playlistContent.split('\n') 111 const lines = playlistContent.split('\n')
@@ -187,7 +192,8 @@ function downloadPlaylistSegments (playlistUrl: string, destinationDir: string,
187 192
188export { 193export {
189 updateMasterHLSPlaylist, 194 updateMasterHLSPlaylist,
190 updateSha256Segments, 195 updateSha256VODSegments,
196 buildSha256Segment,
191 downloadPlaylistSegments, 197 downloadPlaylistSegments,
192 updateStreamingPlaylistsInfohashesIfNeeded 198 updateStreamingPlaylistsInfohashesIfNeeded
193} 199}
diff --git a/server/lib/job-queue/handlers/video-transcoding.ts b/server/lib/job-queue/handlers/video-transcoding.ts
index 7ebef46b4..6659ab716 100644
--- a/server/lib/job-queue/handlers/video-transcoding.ts
+++ b/server/lib/job-queue/handlers/video-transcoding.ts
@@ -84,7 +84,7 @@ async function onVideoFileOptimizerSuccess (videoArg: MVideoWithFile, payload: O
84 if (!videoDatabase) return undefined 84 if (!videoDatabase) return undefined
85 85
86 // Create transcoding jobs if there are enabled resolutions 86 // Create transcoding jobs if there are enabled resolutions
87 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution) 87 const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod')
88 logger.info( 88 logger.info(
89 'Resolutions computed for video %s and origin file resolution of %d.', videoDatabase.uuid, videoFileResolution, 89 'Resolutions computed for video %s and origin file resolution of %d.', videoDatabase.uuid, videoFileResolution,
90 { resolutions: resolutionsEnabled } 90 { resolutions: resolutionsEnabled }
diff --git a/server/lib/live-manager.ts b/server/lib/live-manager.ts
new file mode 100644
index 000000000..f602bfb6d
--- /dev/null
+++ b/server/lib/live-manager.ts
@@ -0,0 +1,310 @@
1
2import { AsyncQueue, queue } from 'async'
3import * as chokidar from 'chokidar'
4import { FfmpegCommand } from 'fluent-ffmpeg'
5import { ensureDir, readdir, remove } from 'fs-extra'
6import { basename, join } from 'path'
7import { computeResolutionsToTranscode, runLiveMuxing, runLiveTranscoding } from '@server/helpers/ffmpeg-utils'
8import { logger } from '@server/helpers/logger'
9import { CONFIG, registerConfigChangedHandler } from '@server/initializers/config'
10import { P2P_MEDIA_LOADER_PEER_VERSION, VIDEO_LIVE, WEBSERVER } from '@server/initializers/constants'
11import { VideoFileModel } from '@server/models/video/video-file'
12import { VideoLiveModel } from '@server/models/video/video-live'
13import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
14import { MStreamingPlaylist, MVideo, MVideoLiveVideo } from '@server/types/models'
15import { VideoState, VideoStreamingPlaylistType } from '@shared/models'
16import { buildSha256Segment } from './hls'
17import { getHLSDirectory } from './video-paths'
18
19const NodeRtmpServer = require('node-media-server/node_rtmp_server')
20const context = require('node-media-server/node_core_ctx')
21const nodeMediaServerLogger = require('node-media-server/node_core_logger')
22
23// Disable node media server logs
24nodeMediaServerLogger.setLogType(0)
25
26const config = {
27 rtmp: {
28 port: CONFIG.LIVE.RTMP.PORT,
29 chunk_size: VIDEO_LIVE.RTMP.CHUNK_SIZE,
30 gop_cache: VIDEO_LIVE.RTMP.GOP_CACHE,
31 ping: VIDEO_LIVE.RTMP.PING,
32 ping_timeout: VIDEO_LIVE.RTMP.PING_TIMEOUT
33 },
34 transcoding: {
35 ffmpeg: 'ffmpeg'
36 }
37}
38
39type SegmentSha256QueueParam = {
40 operation: 'update' | 'delete'
41 videoUUID: string
42 segmentPath: string
43}
44
45class LiveManager {
46
47 private static instance: LiveManager
48
49 private readonly transSessions = new Map<string, FfmpegCommand>()
50 private readonly segmentsSha256 = new Map<string, Map<string, string>>()
51
52 private segmentsSha256Queue: AsyncQueue<SegmentSha256QueueParam>
53 private rtmpServer: any
54
55 private constructor () {
56 }
57
58 init () {
59 this.getContext().nodeEvent.on('postPublish', (sessionId: string, streamPath: string) => {
60 logger.debug('RTMP received stream', { id: sessionId, streamPath })
61
62 const splittedPath = streamPath.split('/')
63 if (splittedPath.length !== 3 || splittedPath[1] !== VIDEO_LIVE.RTMP.BASE_PATH) {
64 logger.warn('Live path is incorrect.', { streamPath })
65 return this.abortSession(sessionId)
66 }
67
68 this.handleSession(sessionId, streamPath, splittedPath[2])
69 .catch(err => logger.error('Cannot handle sessions.', { err }))
70 })
71
72 this.getContext().nodeEvent.on('donePublish', sessionId => {
73 this.abortSession(sessionId)
74 })
75
76 this.segmentsSha256Queue = queue<SegmentSha256QueueParam, Error>((options, cb) => {
77 const promise = options.operation === 'update'
78 ? this.addSegmentSha(options)
79 : Promise.resolve(this.removeSegmentSha(options))
80
81 promise.then(() => cb())
82 .catch(err => {
83 logger.error('Cannot update/remove sha segment %s.', options.segmentPath, { err })
84 cb()
85 })
86 })
87
88 registerConfigChangedHandler(() => {
89 if (!this.rtmpServer && CONFIG.LIVE.ENABLED === true) {
90 this.run()
91 return
92 }
93
94 if (this.rtmpServer && CONFIG.LIVE.ENABLED === false) {
95 this.stop()
96 }
97 })
98 }
99
100 run () {
101 logger.info('Running RTMP server.')
102
103 this.rtmpServer = new NodeRtmpServer(config)
104 this.rtmpServer.run()
105 }
106
107 stop () {
108 logger.info('Stopping RTMP server.')
109
110 this.rtmpServer.stop()
111 this.rtmpServer = undefined
112 }
113
114 getSegmentsSha256 (videoUUID: string) {
115 return this.segmentsSha256.get(videoUUID)
116 }
117
118 private getContext () {
119 return context
120 }
121
122 private abortSession (id: string) {
123 const session = this.getContext().sessions.get(id)
124 if (session) session.stop()
125
126 const transSession = this.transSessions.get(id)
127 if (transSession) transSession.kill('SIGKILL')
128 }
129
130 private async handleSession (sessionId: string, streamPath: string, streamKey: string) {
131 const videoLive = await VideoLiveModel.loadByStreamKey(streamKey)
132 if (!videoLive) {
133 logger.warn('Unknown live video with stream key %s.', streamKey)
134 return this.abortSession(sessionId)
135 }
136
137 const video = videoLive.Video
138 const playlistUrl = WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsMasterPlaylistStaticPath(video.uuid)
139
140 const session = this.getContext().sessions.get(sessionId)
141 const resolutionsEnabled = CONFIG.LIVE.TRANSCODING.ENABLED
142 ? computeResolutionsToTranscode(session.videoHeight, 'live')
143 : []
144
145 logger.info('Will mux/transcode live video of original resolution %d.', session.videoHeight, { resolutionsEnabled })
146
147 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
148 videoId: video.id,
149 playlistUrl,
150 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
151 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, resolutionsEnabled),
152 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
153
154 type: VideoStreamingPlaylistType.HLS
155 }, { returning: true }) as [ MStreamingPlaylist, boolean ]
156
157 video.state = VideoState.PUBLISHED
158 await video.save()
159
160 // FIXME: federation?
161
162 return this.runMuxing({
163 sessionId,
164 videoLive,
165 playlist: videoStreamingPlaylist,
166 streamPath,
167 originalResolution: session.videoHeight,
168 resolutionsEnabled
169 })
170 }
171
172 private async runMuxing (options: {
173 sessionId: string
174 videoLive: MVideoLiveVideo
175 playlist: MStreamingPlaylist
176 streamPath: string
177 resolutionsEnabled: number[]
178 originalResolution: number
179 }) {
180 const { sessionId, videoLive, playlist, streamPath, resolutionsEnabled, originalResolution } = options
181 const allResolutions = resolutionsEnabled.concat([ originalResolution ])
182
183 for (let i = 0; i < allResolutions.length; i++) {
184 const resolution = allResolutions[i]
185
186 VideoFileModel.upsert({
187 resolution,
188 size: -1,
189 extname: '.ts',
190 infoHash: null,
191 fps: -1,
192 videoStreamingPlaylistId: playlist.id
193 }).catch(err => {
194 logger.error('Cannot create file for live streaming.', { err })
195 })
196 }
197
198 const outPath = getHLSDirectory(videoLive.Video)
199 await ensureDir(outPath)
200
201 const rtmpUrl = 'rtmp://127.0.0.1:' + config.rtmp.port + streamPath
202 const ffmpegExec = CONFIG.LIVE.TRANSCODING.ENABLED
203 ? runLiveTranscoding(rtmpUrl, outPath, allResolutions)
204 : runLiveMuxing(rtmpUrl, outPath)
205
206 logger.info('Running live muxing/transcoding.')
207
208 this.transSessions.set(sessionId, ffmpegExec)
209
210 const onFFmpegEnded = () => {
211 watcher.close()
212 .catch(err => logger.error('Cannot close watcher of %s.', outPath, { err }))
213
214 this.onEndTransmuxing(videoLive.Video, playlist, streamPath, outPath)
215 .catch(err => logger.error('Error in closed transmuxing.', { err }))
216 }
217
218 ffmpegExec.on('error', (err, stdout, stderr) => {
219 onFFmpegEnded()
220
221 // Don't care that we killed the ffmpeg process
222 if (err?.message?.includes('SIGKILL')) return
223
224 logger.error('Live transcoding error.', { err, stdout, stderr })
225 })
226
227 ffmpegExec.on('end', () => onFFmpegEnded())
228
229 const videoUUID = videoLive.Video.uuid
230 const watcher = chokidar.watch(outPath + '/*.ts')
231
232 const updateHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'update', segmentPath, videoUUID })
233 const deleteHandler = segmentPath => this.segmentsSha256Queue.push({ operation: 'delete', segmentPath, videoUUID })
234
235 watcher.on('add', p => updateHandler(p))
236 watcher.on('change', p => updateHandler(p))
237 watcher.on('unlink', p => deleteHandler(p))
238 }
239
240 private async onEndTransmuxing (video: MVideo, playlist: MStreamingPlaylist, streamPath: string, outPath: string) {
241 logger.info('RTMP transmuxing for %s ended.', streamPath)
242
243 const files = await readdir(outPath)
244
245 for (const filename of files) {
246 if (
247 filename.endsWith('.ts') ||
248 filename.endsWith('.m3u8') ||
249 filename.endsWith('.mpd') ||
250 filename.endsWith('.m4s') ||
251 filename.endsWith('.tmp')
252 ) {
253 const p = join(outPath, filename)
254
255 remove(p)
256 .catch(err => logger.error('Cannot remove %s.', p, { err }))
257 }
258 }
259
260 playlist.destroy()
261 .catch(err => logger.error('Cannot remove live streaming playlist.', { err }))
262
263 video.state = VideoState.LIVE_ENDED
264 video.save()
265 .catch(err => logger.error('Cannot save new video state of live streaming.', { err }))
266 }
267
268 private async addSegmentSha (options: SegmentSha256QueueParam) {
269 const segmentName = basename(options.segmentPath)
270 logger.debug('Updating live sha segment %s.', options.segmentPath)
271
272 const shaResult = await buildSha256Segment(options.segmentPath)
273
274 if (!this.segmentsSha256.has(options.videoUUID)) {
275 this.segmentsSha256.set(options.videoUUID, new Map())
276 }
277
278 const filesMap = this.segmentsSha256.get(options.videoUUID)
279 filesMap.set(segmentName, shaResult)
280 }
281
282 private removeSegmentSha (options: SegmentSha256QueueParam) {
283 const segmentName = basename(options.segmentPath)
284
285 logger.debug('Removing live sha segment %s.', options.segmentPath)
286
287 const filesMap = this.segmentsSha256.get(options.videoUUID)
288 if (!filesMap) {
289 logger.warn('Unknown files map to remove sha for %s.', options.videoUUID)
290 return
291 }
292
293 if (!filesMap.has(segmentName)) {
294 logger.warn('Unknown segment in files map for video %s and segment %s.', options.videoUUID, options.segmentPath)
295 return
296 }
297
298 filesMap.delete(segmentName)
299 }
300
301 static get Instance () {
302 return this.instance || (this.instance = new this())
303 }
304}
305
306// ---------------------------------------------------------------------------
307
308export {
309 LiveManager
310}
diff --git a/server/lib/video-paths.ts b/server/lib/video-paths.ts
index a35661f02..b6cb39d25 100644
--- a/server/lib/video-paths.ts
+++ b/server/lib/video-paths.ts
@@ -27,7 +27,8 @@ function generateWebTorrentVideoName (uuid: string, resolution: number, extname:
27function getVideoFilePath (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile, isRedundancy = false) { 27function getVideoFilePath (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile, isRedundancy = false) {
28 if (isStreamingPlaylist(videoOrPlaylist)) { 28 if (isStreamingPlaylist(videoOrPlaylist)) {
29 const video = extractVideo(videoOrPlaylist) 29 const video = extractVideo(videoOrPlaylist)
30 return join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid, getVideoFilename(videoOrPlaylist, videoFile)) 30
31 return join(getHLSDirectory(video), getVideoFilename(videoOrPlaylist, videoFile))
31 } 32 }
32 33
33 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR 34 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
diff --git a/server/lib/video-transcoding.ts b/server/lib/video-transcoding.ts
index 5a2dbc9f7..a7b73a30d 100644
--- a/server/lib/video-transcoding.ts
+++ b/server/lib/video-transcoding.ts
@@ -13,13 +13,14 @@ import { copyFile, ensureDir, move, remove, stat } from 'fs-extra'
13import { logger } from '../helpers/logger' 13import { logger } from '../helpers/logger'
14import { VideoResolution } from '../../shared/models/videos' 14import { VideoResolution } from '../../shared/models/videos'
15import { VideoFileModel } from '../models/video/video-file' 15import { VideoFileModel } from '../models/video/video-file'
16import { updateMasterHLSPlaylist, updateSha256Segments } from './hls' 16import { updateMasterHLSPlaylist, updateSha256VODSegments } from './hls'
17import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist' 17import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
18import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type' 18import { VideoStreamingPlaylistType } from '../../shared/models/videos/video-streaming-playlist.type'
19import { CONFIG } from '../initializers/config' 19import { CONFIG } from '../initializers/config'
20import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models' 20import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoWithAllFiles, MVideoWithFile } from '@server/types/models'
21import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' 21import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
22import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths' 22import { generateVideoStreamingPlaylistName, getVideoFilename, getVideoFilePath } from './video-paths'
23import { spawn } from 'child_process'
23 24
24/** 25/**
25 * Optimize the original video file and replace it. The resolution is not changed. 26 * Optimize the original video file and replace it. The resolution is not changed.
@@ -182,7 +183,7 @@ async function generateHlsPlaylist (video: MVideoWithFile, resolution: VideoReso
182 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({ 183 const [ videoStreamingPlaylist ] = await VideoStreamingPlaylistModel.upsert({
183 videoId: video.id, 184 videoId: video.id,
184 playlistUrl, 185 playlistUrl,
185 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid), 186 segmentsSha256Url: WEBSERVER.URL + VideoStreamingPlaylistModel.getHlsSha256SegmentsStaticPath(video.uuid, video.isLive),
186 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, video.VideoFiles), 187 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrl, video.VideoFiles),
187 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, 188 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
188 189
@@ -213,7 +214,7 @@ async function generateHlsPlaylist (video: MVideoWithFile, resolution: VideoReso
213 video.setHLSPlaylist(videoStreamingPlaylist) 214 video.setHLSPlaylist(videoStreamingPlaylist)
214 215
215 await updateMasterHLSPlaylist(video) 216 await updateMasterHLSPlaylist(video)
216 await updateSha256Segments(video) 217 await updateSha256VODSegments(video)
217 218
218 return video 219 return video
219} 220}
diff --git a/server/lib/video.ts b/server/lib/video.ts
new file mode 100644
index 000000000..a28f31529
--- /dev/null
+++ b/server/lib/video.ts
@@ -0,0 +1,31 @@
1
2import { VideoModel } from '@server/models/video/video'
3import { FilteredModelAttributes } from '@server/types'
4import { VideoCreate, VideoPrivacy, VideoState } from '@shared/models'
5
6function buildLocalVideoFromCreate (videoInfo: VideoCreate, channelId: number): FilteredModelAttributes<VideoModel> {
7 return {
8 name: videoInfo.name,
9 remote: false,
10 category: videoInfo.category,
11 licence: videoInfo.licence,
12 language: videoInfo.language,
13 commentsEnabled: videoInfo.commentsEnabled !== false, // If the value is not "false", the default is "true"
14 downloadEnabled: videoInfo.downloadEnabled !== false,
15 waitTranscoding: videoInfo.waitTranscoding || false,
16 state: VideoState.WAITING_FOR_LIVE,
17 nsfw: videoInfo.nsfw || false,
18 description: videoInfo.description,
19 support: videoInfo.support,
20 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
21 duration: 0,
22 channelId: channelId,
23 originallyPublishedAt: videoInfo.originallyPublishedAt
24 }
25}
26
27// ---------------------------------------------------------------------------
28
29export {
30 buildLocalVideoFromCreate
31}