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