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