]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/hls.ts
5a7d61dee6034ad180cb6fbcdf8671f3531c1506
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
1 import { VideoModel } from '../models/video/video'
2 import { basename, dirname, join } from 'path'
3 import { CONFIG, HLS_STREAMING_PLAYLIST_DIRECTORY, 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
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 }
27
28 async function updateMasterHLSPlaylist (video: VideoModel) {
29 const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
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) {
56 const json: { [filename: string]: { [range: string]: string } } = {}
57
58 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
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))
66
67 // Maybe the playlist is not generated for this resolution yet
68 if (!await pathExists(playlistPath)) continue
69
70 const playlistContent = await readFile(playlistPath)
71 const ranges = getRangesFromPlaylist(playlistContent.toString())
72
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
84 }
85
86 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
87 await outputJSON(outputPath, json)
88 }
89
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+)$/
94
95 for (const line of lines) {
96 const captured = regex.exec(line)
97
98 if (captured) {
99 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
100 }
101 }
102
103 return ranges
104 }
105
106 function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
107 let timer
108
109 logger.info('Importing HLS playlist %s', playlistUrl)
110
111 return new Promise<string>(async (res, rej) => {
112 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
113
114 await ensureDir(tmpDirectory)
115
116 timer = setTimeout(() => {
117 deleteTmpDirectory(tmpDirectory)
118
119 return rej(new Error('HLS download timeout.'))
120 }, timeout)
121
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
134 const bodyKBLimit = 10 * 1000 * 1000 // 10GB
135 await doRequestAndSaveToFile({ uri: fileUrl }, destPath, bodyKBLimit)
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)
147 }
148 })
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 }
170 }
171
172 // ---------------------------------------------------------------------------
173
174 export {
175 updateMasterHLSPlaylist,
176 updateSha256Segments,
177 downloadPlaylistSegments,
178 updateStreamingPlaylistsInfohashesIfNeeded
179 }
180
181 // ---------------------------------------------------------------------------