]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/hls.ts
Move test functions outside extra-utils
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
CommitLineData
0305db28 1import { close, ensureDir, move, open, outputJSON, read, readFile, remove, stat, writeFile } from 'fs-extra'
daf6e480
C
2import { flatten, uniq } from 'lodash'
3import { basename, dirname, join } from 'path'
e1ab52d7 4import { MStreamingPlaylistFilesVideo, MVideo, MVideoUUID } from '@server/types/models'
c55e3d72 5import { sha256 } from '@shared/core-utils/common/crypto'
daf6e480 6import { getAudioStreamCodec, getVideoStreamCodec, getVideoStreamSize } from '../helpers/ffprobe-utils'
09209296 7import { logger } from '../helpers/logger'
4c280004
C
8import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
9import { generateRandomString } from '../helpers/utils'
6dd9de95 10import { CONFIG } from '../initializers/config'
7b0c61e7 11import { P2P_MEDIA_LOADER_PEER_VERSION, REQUEST_TIMEOUTS } from '../initializers/constants'
74dc3bca 12import { sequelizeTypescript } from '../initializers/database'
daf6e480
C
13import { VideoFileModel } from '../models/video/video-file'
14import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
0305db28
JB
15import { getHlsResolutionPlaylistFilename } from './paths'
16import { VideoPathManager } from './video-path-manager'
ae9bbed4
C
17
18async function updateStreamingPlaylistsInfohashesIfNeeded () {
19 const playlistsToUpdate = await VideoStreamingPlaylistModel.listByIncorrectPeerVersion()
20
21 // Use separate SQL queries, because we could have many videos to update
22 for (const playlist of playlistsToUpdate) {
23 await sequelizeTypescript.transaction(async t => {
24 const videoFiles = await VideoFileModel.listByStreamingPlaylist(playlist.id, t)
25
764b1a14 26 playlist.assignP2PMediaLoaderInfoHashes(playlist.Video, videoFiles)
0e9c48c2 27 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
764b1a14 28
ae9bbed4
C
29 await playlist.save({ transaction: t })
30 })
31 }
32}
09209296 33
e1ab52d7 34async function updateMasterHLSPlaylist (video: MVideo, playlist: MStreamingPlaylistFilesVideo) {
09209296 35 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
09209296 36
764b1a14
C
37 for (const file of playlist.VideoFiles) {
38 const playlistFilename = getHlsResolutionPlaylistFilename(file.filename)
83903cb6 39
ad5db104 40 await VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(playlist), async videoFilePath => {
0305db28 41 const size = await getVideoStreamSize(videoFilePath)
09209296 42
0305db28
JB
43 const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
44 const resolution = `RESOLUTION=${size.width}x${size.height}`
09209296 45
0305db28
JB
46 let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
47 if (file.fps) line += ',FRAME-RATE=' + file.fps
09209296 48
0305db28
JB
49 const codecs = await Promise.all([
50 getVideoStreamCodec(videoFilePath),
51 getAudioStreamCodec(videoFilePath)
52 ])
d7b1c7b4 53
0305db28 54 line += `,CODECS="${codecs.filter(c => !!c).join(',')}"`
52201311 55
0305db28
JB
56 masterPlaylists.push(line)
57 masterPlaylists.push(playlistFilename)
58 })
09209296
C
59 }
60
0305db28
JB
61 await VideoPathManager.Instance.makeAvailablePlaylistFile(playlist, playlist.playlistFilename, masterPlaylistPath => {
62 return writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
63 })
09209296
C
64}
65
e1ab52d7 66async function updateSha256VODSegments (video: MVideoUUID, playlist: MStreamingPlaylistFilesVideo) {
4c280004
C
67 const json: { [filename: string]: { [range: string]: string } } = {}
68
4c280004 69 // For all the resolutions available for this video
764b1a14 70 for (const file of playlist.VideoFiles) {
4c280004 71 const rangeHashes: { [range: string]: string } = {}
ad5db104 72 const fileWithPlaylist = file.withVideoOrPlaylist(playlist)
4c280004 73
ad5db104 74 await VideoPathManager.Instance.makeAvailableVideoFile(fileWithPlaylist, videoPath => {
09209296 75
ad5db104 76 return VideoPathManager.Instance.makeAvailableResolutionPlaylistFile(fileWithPlaylist, async resolutionPlaylistPath => {
0305db28
JB
77 const playlistContent = await readFile(resolutionPlaylistPath)
78 const ranges = getRangesFromPlaylist(playlistContent.toString())
09209296 79
0305db28
JB
80 const fd = await open(videoPath, 'r')
81 for (const range of ranges) {
82 const buf = Buffer.alloc(range.length)
83 await read(fd, buf, 0, range.length, range.offset)
09209296 84
0305db28
JB
85 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
86 }
87 await close(fd)
4c280004 88
0305db28
JB
89 const videoFilename = file.filename
90 json[videoFilename] = rangeHashes
91 })
92 })
09209296
C
93 }
94
0305db28 95 const outputPath = VideoPathManager.Instance.getFSHLSOutputPath(video, playlist.segmentsSha256Filename)
09209296
C
96 await outputJSON(outputPath, json)
97}
98
c6c0fa6c
C
99async function buildSha256Segment (segmentPath: string) {
100 const buf = await readFile(segmentPath)
101 return sha256(buf)
102}
103
18998c45 104function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number, bodyKBLimit: number) {
4c280004 105 let timer
18998c45 106 let remainingBodyKBLimit = bodyKBLimit
09209296 107
4c280004 108 logger.info('Importing HLS playlist %s', playlistUrl)
09209296 109
ba5a8d89 110 return new Promise<void>(async (res, rej) => {
4c280004 111 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
09209296 112
4c280004 113 await ensureDir(tmpDirectory)
09209296
C
114
115 timer = setTimeout(() => {
4c280004 116 deleteTmpDirectory(tmpDirectory)
09209296
C
117
118 return rej(new Error('HLS download timeout.'))
119 }, timeout)
120
4c280004
C
121 try {
122 // Fetch master playlist
123 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
124
125 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
126 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
127
128 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
129
130 for (const fileUrl of fileUrls) {
131 const destPath = join(tmpDirectory, basename(fileUrl))
132
a5ee023c 133 await doRequestAndSaveToFile(fileUrl, destPath, { bodyKBLimit: remainingBodyKBLimit, timeout: REQUEST_TIMEOUTS.REDUNDANCY })
18998c45
C
134
135 const { size } = await stat(destPath)
136 remainingBodyKBLimit -= (size / 1000)
137
138 logger.debug('Downloaded HLS playlist file %s with %d kB remained limit.', fileUrl, Math.floor(remainingBodyKBLimit))
4c280004
C
139 }
140
141 clearTimeout(timer)
142
143 await move(tmpDirectory, destinationDir, { overwrite: true })
144
145 return res()
146 } catch (err) {
147 deleteTmpDirectory(tmpDirectory)
148
149 return rej(err)
09209296
C
150 }
151 })
4c280004
C
152
153 function deleteTmpDirectory (directory: string) {
154 remove(directory)
155 .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
156 }
157
158 async function fetchUniqUrls (playlistUrl: string) {
db4b15f2 159 const { body } = await doRequest(playlistUrl)
4c280004
C
160
161 if (!body) return []
162
163 const urls = body.split('\n')
164 .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
165 .map(url => {
166 if (url.startsWith('http://') || url.startsWith('https://')) return url
167
168 return `${dirname(playlistUrl)}/${url}`
169 })
170
171 return uniq(urls)
172 }
09209296
C
173}
174
175// ---------------------------------------------------------------------------
176
177export {
178 updateMasterHLSPlaylist,
c6c0fa6c
C
179 updateSha256VODSegments,
180 buildSha256Segment,
ae9bbed4
C
181 downloadPlaylistSegments,
182 updateStreamingPlaylistsInfohashesIfNeeded
09209296
C
183}
184
185// ---------------------------------------------------------------------------
b5b68755
C
186
187function getRangesFromPlaylist (playlistContent: string) {
188 const ranges: { offset: number, length: number }[] = []
189 const lines = playlistContent.split('\n')
190 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
191
192 for (const line of lines) {
193 const captured = regex.exec(line)
194
195 if (captured) {
196 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
197 }
198 }
199
200 return ranges
201}