]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/hls.ts
Instance homepage support (#4007)
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
1 import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
2 import { flatten, uniq } from 'lodash'
3 import { basename, dirname, join } from 'path'
4 import { MVideoWithFile } from '@server/types/models'
5 import { sha256 } from '../helpers/core-utils'
6 import { getAudioStreamCodec, getVideoStreamCodec, getVideoStreamSize } from '../helpers/ffprobe-utils'
7 import { logger } from '../helpers/logger'
8 import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
9 import { generateRandomString } from '../helpers/utils'
10 import { CONFIG } from '../initializers/config'
11 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants'
12 import { sequelizeTypescript } from '../initializers/database'
13 import { VideoFileModel } from '../models/video/video-file'
14 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
15 import { getVideoFilePath } from './video-paths'
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
25 playlist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlist.playlistUrl, videoFiles)
26 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
27 await playlist.save({ transaction: t })
28 })
29 }
30 }
31
32 async function updateMasterHLSPlaylist (video: MVideoWithFile) {
33 const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
34 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
35 const masterPlaylistPath = join(directory, VideoStreamingPlaylistModel.getMasterHlsPlaylistFilename())
36 const streamingPlaylist = video.getHLSPlaylist()
37
38 for (const file of streamingPlaylist.VideoFiles) {
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
43 const videoFilePath = getVideoFilePath(streamingPlaylist, file)
44
45 const size = await getVideoStreamSize(videoFilePath)
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
53 const codecs = await Promise.all([
54 getVideoStreamCodec(videoFilePath),
55 getAudioStreamCodec(videoFilePath)
56 ])
57
58 line += `,CODECS="${codecs.filter(c => !!c).join(',')}"`
59
60 masterPlaylists.push(line)
61 masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
62 }
63
64 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
65 }
66
67 async function updateSha256VODSegments (video: MVideoWithFile) {
68 const json: { [filename: string]: { [range: string]: string } } = {}
69
70 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
71 const hlsPlaylist = video.getHLSPlaylist()
72
73 // For all the resolutions available for this video
74 for (const file of hlsPlaylist.VideoFiles) {
75 const rangeHashes: { [range: string]: string } = {}
76
77 const videoPath = getVideoFilePath(hlsPlaylist, file)
78 const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
79
80 // Maybe the playlist is not generated for this resolution yet
81 if (!await pathExists(playlistPath)) continue
82
83 const playlistContent = await readFile(playlistPath)
84 const ranges = getRangesFromPlaylist(playlistContent.toString())
85
86 const fd = await open(videoPath, 'r')
87 for (const range of ranges) {
88 const buf = Buffer.alloc(range.length)
89 await read(fd, buf, 0, range.length, range.offset)
90
91 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
92 }
93 await close(fd)
94
95 const videoFilename = file.filename
96 json[videoFilename] = rangeHashes
97 }
98
99 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
100 await outputJSON(outputPath, json)
101 }
102
103 async function buildSha256Segment (segmentPath: string) {
104 const buf = await readFile(segmentPath)
105 return sha256(buf)
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<void>(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(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(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 updateSha256VODSegments,
179 buildSha256Segment,
180 downloadPlaylistSegments,
181 updateStreamingPlaylistsInfohashesIfNeeded
182 }
183
184 // ---------------------------------------------------------------------------
185
186 function getRangesFromPlaylist (playlistContent: string) {
187 const ranges: { offset: number, length: number }[] = []
188 const lines = playlistContent.split('\n')
189 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
190
191 for (const line of lines) {
192 const captured = regex.exec(line)
193
194 if (captured) {
195 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
196 }
197 }
198
199 return ranges
200 }