]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/hls.ts
943721dd779c6f485c71a14dac3a31e6d3198b5f
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
1 import { basename, dirname, join } from 'path'
2 import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants'
3 import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
4 import { getVideoFileSize } from '../helpers/ffmpeg-utils'
5 import { sha256 } from '../helpers/core-utils'
6 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
7 import { logger } from '../helpers/logger'
8 import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
9 import { generateRandomString } from '../helpers/utils'
10 import { flatten, uniq } from 'lodash'
11 import { VideoFileModel } from '../models/video/video-file'
12 import { CONFIG } from '../initializers/config'
13 import { sequelizeTypescript } from '../initializers/database'
14 import { MVideoWithFile } from '@server/typings/models'
15 import { getVideoFilename, 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 getVideoFileSize(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 masterPlaylists.push(line)
54 masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
55 }
56
57 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
58 }
59
60 async function updateSha256Segments (video: MVideoWithFile) {
61 const json: { [filename: string]: { [range: string]: string } } = {}
62
63 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
64 const hlsPlaylist = video.getHLSPlaylist()
65
66 // For all the resolutions available for this video
67 for (const file of hlsPlaylist.VideoFiles) {
68 const rangeHashes: { [range: string]: string } = {}
69
70 const videoPath = getVideoFilePath(hlsPlaylist, file)
71 const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
72
73 // Maybe the playlist is not generated for this resolution yet
74 if (!await pathExists(playlistPath)) continue
75
76 const playlistContent = await readFile(playlistPath)
77 const ranges = getRangesFromPlaylist(playlistContent.toString())
78
79 const fd = await open(videoPath, 'r')
80 for (const range of ranges) {
81 const buf = Buffer.alloc(range.length)
82 await read(fd, buf, 0, range.length, range.offset)
83
84 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
85 }
86 await close(fd)
87
88 const videoFilename = getVideoFilename(hlsPlaylist, file)
89 json[videoFilename] = rangeHashes
90 }
91
92 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
93 await outputJSON(outputPath, json)
94 }
95
96 function getRangesFromPlaylist (playlistContent: string) {
97 const ranges: { offset: number, length: number }[] = []
98 const lines = playlistContent.split('\n')
99 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
100
101 for (const line of lines) {
102 const captured = regex.exec(line)
103
104 if (captured) {
105 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
106 }
107 }
108
109 return ranges
110 }
111
112 function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
113 let timer
114
115 logger.info('Importing HLS playlist %s', playlistUrl)
116
117 return new Promise<string>(async (res, rej) => {
118 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
119
120 await ensureDir(tmpDirectory)
121
122 timer = setTimeout(() => {
123 deleteTmpDirectory(tmpDirectory)
124
125 return rej(new Error('HLS download timeout.'))
126 }, timeout)
127
128 try {
129 // Fetch master playlist
130 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
131
132 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
133 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
134
135 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
136
137 for (const fileUrl of fileUrls) {
138 const destPath = join(tmpDirectory, basename(fileUrl))
139
140 const bodyKBLimit = 10 * 1000 * 1000 // 10GB
141 await doRequestAndSaveToFile({ uri: fileUrl }, destPath, bodyKBLimit)
142 }
143
144 clearTimeout(timer)
145
146 await move(tmpDirectory, destinationDir, { overwrite: true })
147
148 return res()
149 } catch (err) {
150 deleteTmpDirectory(tmpDirectory)
151
152 return rej(err)
153 }
154 })
155
156 function deleteTmpDirectory (directory: string) {
157 remove(directory)
158 .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
159 }
160
161 async function fetchUniqUrls (playlistUrl: string) {
162 const { body } = await doRequest<string>({ uri: playlistUrl })
163
164 if (!body) return []
165
166 const urls = body.split('\n')
167 .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
168 .map(url => {
169 if (url.startsWith('http://') || url.startsWith('https://')) return url
170
171 return `${dirname(playlistUrl)}/${url}`
172 })
173
174 return uniq(urls)
175 }
176 }
177
178 // ---------------------------------------------------------------------------
179
180 export {
181 updateMasterHLSPlaylist,
182 updateSha256Segments,
183 downloadPlaylistSegments,
184 updateStreamingPlaylistsInfohashesIfNeeded
185 }
186
187 // ---------------------------------------------------------------------------