]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/hls.ts
Add support for saving video files to object storage (#4290)
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
1 import { close, ensureDir, move, open, outputJSON, read, readFile, remove, stat, writeFile } from 'fs-extra'
2 import { flatten, uniq } from 'lodash'
3 import { basename, dirname, join } from 'path'
4 import { MStreamingPlaylistFilesVideo, 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 { 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 { getHlsResolutionPlaylistFilename } from './paths'
16 import { VideoPathManager } from './video-path-manager'
17
18 async 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
26 playlist.assignP2PMediaLoaderInfoHashes(playlist.Video, videoFiles)
27 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
28
29 await playlist.save({ transaction: t })
30 })
31 }
32 }
33
34 async function updateMasterHLSPlaylist (video: MVideoWithFile, playlist: MStreamingPlaylistFilesVideo) {
35 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
36
37 for (const file of playlist.VideoFiles) {
38 const playlistFilename = getHlsResolutionPlaylistFilename(file.filename)
39
40 await VideoPathManager.Instance.makeAvailableVideoFile(playlist, file, async videoFilePath => {
41 const size = await getVideoStreamSize(videoFilePath)
42
43 const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
44 const resolution = `RESOLUTION=${size.width}x${size.height}`
45
46 let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
47 if (file.fps) line += ',FRAME-RATE=' + file.fps
48
49 const codecs = await Promise.all([
50 getVideoStreamCodec(videoFilePath),
51 getAudioStreamCodec(videoFilePath)
52 ])
53
54 line += `,CODECS="${codecs.filter(c => !!c).join(',')}"`
55
56 masterPlaylists.push(line)
57 masterPlaylists.push(playlistFilename)
58 })
59 }
60
61 await VideoPathManager.Instance.makeAvailablePlaylistFile(playlist, playlist.playlistFilename, masterPlaylistPath => {
62 return writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
63 })
64 }
65
66 async function updateSha256VODSegments (video: MVideoWithFile, playlist: MStreamingPlaylistFilesVideo) {
67 const json: { [filename: string]: { [range: string]: string } } = {}
68
69 // For all the resolutions available for this video
70 for (const file of playlist.VideoFiles) {
71 const rangeHashes: { [range: string]: string } = {}
72
73 await VideoPathManager.Instance.makeAvailableVideoFile(playlist, file, videoPath => {
74
75 return VideoPathManager.Instance.makeAvailableResolutionPlaylistFile(playlist, file, async resolutionPlaylistPath => {
76 const playlistContent = await readFile(resolutionPlaylistPath)
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 = file.filename
89 json[videoFilename] = rangeHashes
90 })
91 })
92 }
93
94 const outputPath = VideoPathManager.Instance.getFSHLSOutputPath(video, playlist.segmentsSha256Filename)
95 await outputJSON(outputPath, json)
96 }
97
98 async function buildSha256Segment (segmentPath: string) {
99 const buf = await readFile(segmentPath)
100 return sha256(buf)
101 }
102
103 function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number, bodyKBLimit: number) {
104 let timer
105 let remainingBodyKBLimit = bodyKBLimit
106
107 logger.info('Importing HLS playlist %s', playlistUrl)
108
109 return new Promise<void>(async (res, rej) => {
110 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
111
112 await ensureDir(tmpDirectory)
113
114 timer = setTimeout(() => {
115 deleteTmpDirectory(tmpDirectory)
116
117 return rej(new Error('HLS download timeout.'))
118 }, timeout)
119
120 try {
121 // Fetch master playlist
122 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
123
124 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
125 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
126
127 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
128
129 for (const fileUrl of fileUrls) {
130 const destPath = join(tmpDirectory, basename(fileUrl))
131
132 await doRequestAndSaveToFile(fileUrl, destPath, { bodyKBLimit: remainingBodyKBLimit })
133
134 const { size } = await stat(destPath)
135 remainingBodyKBLimit -= (size / 1000)
136
137 logger.debug('Downloaded HLS playlist file %s with %d kB remained limit.', fileUrl, Math.floor(remainingBodyKBLimit))
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 }