]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/hls.ts
Move config in its own file
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
1 import { VideoModel } from '../models/video/video'
2 import { basename, dirname, join } from 'path'
3 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION, sequelizeTypescript } from '../initializers'
4 import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
5 import { getVideoFileSize } from '../helpers/ffmpeg-utils'
6 import { sha256 } from '../helpers/core-utils'
7 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
8 import { logger } from '../helpers/logger'
9 import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
10 import { generateRandomString } from '../helpers/utils'
11 import { flatten, uniq } from 'lodash'
12 import { VideoFileModel } from '../models/video/video-file'
13 import { CONFIG } from '../initializers/config'
14
15 async function updateStreamingPlaylistsInfohashesIfNeeded () {
16 const playlistsToUpdate = await VideoStreamingPlaylistModel.listByIncorrectPeerVersion()
17
18 // Use separate SQL queries, because we could have many videos to update
19 for (const playlist of playlistsToUpdate) {
20 await sequelizeTypescript.transaction(async t => {
21 const videoFiles = await VideoFileModel.listByStreamingPlaylist(playlist.id, t)
22
23 playlist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlist.playlistUrl, videoFiles)
24 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
25 await playlist.save({ transaction: t })
26 })
27 }
28 }
29
30 async function updateMasterHLSPlaylist (video: VideoModel) {
31 const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
32 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
33 const masterPlaylistPath = join(directory, VideoStreamingPlaylistModel.getMasterHlsPlaylistFilename())
34
35 for (const file of video.VideoFiles) {
36 // If we did not generated a playlist for this resolution, skip
37 const filePlaylistPath = join(directory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
38 if (await pathExists(filePlaylistPath) === false) continue
39
40 const videoFilePath = video.getVideoFilePath(file)
41
42 const size = await getVideoFileSize(videoFilePath)
43
44 const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
45 const resolution = `RESOLUTION=${size.width}x${size.height}`
46
47 let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
48 if (file.fps) line += ',FRAME-RATE=' + file.fps
49
50 masterPlaylists.push(line)
51 masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
52 }
53
54 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
55 }
56
57 async function updateSha256Segments (video: VideoModel) {
58 const json: { [filename: string]: { [range: string]: string } } = {}
59
60 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
61
62 // For all the resolutions available for this video
63 for (const file of video.VideoFiles) {
64 const rangeHashes: { [range: string]: string } = {}
65
66 const videoPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution))
67 const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
68
69 // Maybe the playlist is not generated for this resolution yet
70 if (!await pathExists(playlistPath)) continue
71
72 const playlistContent = await readFile(playlistPath)
73 const ranges = getRangesFromPlaylist(playlistContent.toString())
74
75 const fd = await open(videoPath, 'r')
76 for (const range of ranges) {
77 const buf = Buffer.alloc(range.length)
78 await read(fd, buf, 0, range.length, range.offset)
79
80 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
81 }
82 await close(fd)
83
84 const videoFilename = VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution)
85 json[videoFilename] = rangeHashes
86 }
87
88 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
89 await outputJSON(outputPath, json)
90 }
91
92 function getRangesFromPlaylist (playlistContent: string) {
93 const ranges: { offset: number, length: number }[] = []
94 const lines = playlistContent.split('\n')
95 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
96
97 for (const line of lines) {
98 const captured = regex.exec(line)
99
100 if (captured) {
101 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
102 }
103 }
104
105 return ranges
106 }
107
108 function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
109 let timer
110
111 logger.info('Importing HLS playlist %s', playlistUrl)
112
113 return new Promise<string>(async (res, rej) => {
114 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
115
116 await ensureDir(tmpDirectory)
117
118 timer = setTimeout(() => {
119 deleteTmpDirectory(tmpDirectory)
120
121 return rej(new Error('HLS download timeout.'))
122 }, timeout)
123
124 try {
125 // Fetch master playlist
126 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
127
128 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
129 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
130
131 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
132
133 for (const fileUrl of fileUrls) {
134 const destPath = join(tmpDirectory, basename(fileUrl))
135
136 const bodyKBLimit = 10 * 1000 * 1000 // 10GB
137 await doRequestAndSaveToFile({ uri: fileUrl }, destPath, bodyKBLimit)
138 }
139
140 clearTimeout(timer)
141
142 await move(tmpDirectory, destinationDir, { overwrite: true })
143
144 return res()
145 } catch (err) {
146 deleteTmpDirectory(tmpDirectory)
147
148 return rej(err)
149 }
150 })
151
152 function deleteTmpDirectory (directory: string) {
153 remove(directory)
154 .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
155 }
156
157 async function fetchUniqUrls (playlistUrl: string) {
158 const { body } = await doRequest<string>({ uri: playlistUrl })
159
160 if (!body) return []
161
162 const urls = body.split('\n')
163 .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
164 .map(url => {
165 if (url.startsWith('http://') || url.startsWith('https://')) return url
166
167 return `${dirname(playlistUrl)}/${url}`
168 })
169
170 return uniq(urls)
171 }
172 }
173
174 // ---------------------------------------------------------------------------
175
176 export {
177 updateMasterHLSPlaylist,
178 updateSha256Segments,
179 downloadPlaylistSegments,
180 updateStreamingPlaylistsInfohashesIfNeeded
181 }
182
183 // ---------------------------------------------------------------------------