]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/hls.ts
Generate random uuid for video files
[github/Chocobozzz/PeerTube.git] / server / lib / hls.ts
CommitLineData
4c280004 1import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
daf6e480
C
2import { flatten, uniq } from 'lodash'
3import { basename, dirname, join } from 'path'
4import { MVideoWithFile } from '@server/types/models'
09209296 5import { sha256 } from '../helpers/core-utils'
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'
daf6e480 11import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } 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'
90a8bd30 15import { getVideoFilePath } from './video-paths'
ae9bbed4
C
16
17async 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
594d0c6a 25 playlist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlist.playlistUrl, videoFiles)
0e9c48c2 26 playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
ae9bbed4
C
27 await playlist.save({ transaction: t })
28 })
29 }
30}
09209296 31
453e83ea 32async function updateMasterHLSPlaylist (video: MVideoWithFile) {
9c6ca37f 33 const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
09209296
C
34 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
35 const masterPlaylistPath = join(directory, VideoStreamingPlaylistModel.getMasterHlsPlaylistFilename())
d7a25329 36 const streamingPlaylist = video.getHLSPlaylist()
09209296 37
d7a25329 38 for (const file of streamingPlaylist.VideoFiles) {
83903cb6
C
39 const playlistFilename = VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution)
40
09209296 41 // If we did not generated a playlist for this resolution, skip
83903cb6 42 const filePlaylistPath = join(directory, playlistFilename)
09209296
C
43 if (await pathExists(filePlaylistPath) === false) continue
44
d7a25329 45 const videoFilePath = getVideoFilePath(streamingPlaylist, file)
09209296 46
52201311 47 const size = await getVideoStreamSize(videoFilePath)
09209296
C
48
49 const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
50 const resolution = `RESOLUTION=${size.width}x${size.height}`
51
52 let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
53 if (file.fps) line += ',FRAME-RATE=' + file.fps
54
66f77f63 55 const codecs = await Promise.all([
56 getVideoStreamCodec(videoFilePath),
57 getAudioStreamCodec(videoFilePath)
58 ])
d7b1c7b4 59
66f77f63 60 line += `,CODECS="${codecs.filter(c => !!c).join(',')}"`
52201311 61
09209296 62 masterPlaylists.push(line)
83903cb6 63 masterPlaylists.push(playlistFilename)
09209296
C
64 }
65
66 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
67}
68
c6c0fa6c 69async function updateSha256VODSegments (video: MVideoWithFile) {
4c280004
C
70 const json: { [filename: string]: { [range: string]: string } } = {}
71
9c6ca37f 72 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
d7a25329 73 const hlsPlaylist = video.getHLSPlaylist()
4c280004
C
74
75 // For all the resolutions available for this video
d7a25329 76 for (const file of hlsPlaylist.VideoFiles) {
4c280004
C
77 const rangeHashes: { [range: string]: string } = {}
78
d7a25329 79 const videoPath = getVideoFilePath(hlsPlaylist, file)
4c280004 80 const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
09209296 81
4c280004
C
82 // Maybe the playlist is not generated for this resolution yet
83 if (!await pathExists(playlistPath)) continue
09209296 84
4c280004
C
85 const playlistContent = await readFile(playlistPath)
86 const ranges = getRangesFromPlaylist(playlistContent.toString())
09209296 87
4c280004
C
88 const fd = await open(videoPath, 'r')
89 for (const range of ranges) {
90 const buf = Buffer.alloc(range.length)
91 await read(fd, buf, 0, range.length, range.offset)
92
93 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
94 }
95 await close(fd)
96
90a8bd30 97 const videoFilename = file.filename
4c280004 98 json[videoFilename] = rangeHashes
09209296
C
99 }
100
4c280004 101 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
09209296
C
102 await outputJSON(outputPath, json)
103}
104
c6c0fa6c
C
105async function buildSha256Segment (segmentPath: string) {
106 const buf = await readFile(segmentPath)
107 return sha256(buf)
108}
109
4c280004
C
110function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
111 let timer
09209296 112
4c280004 113 logger.info('Importing HLS playlist %s', playlistUrl)
09209296 114
ba5a8d89 115 return new Promise<void>(async (res, rej) => {
4c280004 116 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
09209296 117
4c280004 118 await ensureDir(tmpDirectory)
09209296
C
119
120 timer = setTimeout(() => {
4c280004 121 deleteTmpDirectory(tmpDirectory)
09209296
C
122
123 return rej(new Error('HLS download timeout.'))
124 }, timeout)
125
4c280004
C
126 try {
127 // Fetch master playlist
128 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
129
130 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
131 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
132
133 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
134
135 for (const fileUrl of fileUrls) {
136 const destPath = join(tmpDirectory, basename(fileUrl))
137
bfe2ef6b 138 const bodyKBLimit = 10 * 1000 * 1000 // 10GB
db4b15f2 139 await doRequestAndSaveToFile(fileUrl, destPath, { bodyKBLimit })
4c280004
C
140 }
141
142 clearTimeout(timer)
143
144 await move(tmpDirectory, destinationDir, { overwrite: true })
145
146 return res()
147 } catch (err) {
148 deleteTmpDirectory(tmpDirectory)
149
150 return rej(err)
09209296
C
151 }
152 })
4c280004
C
153
154 function deleteTmpDirectory (directory: string) {
155 remove(directory)
156 .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
157 }
158
159 async function fetchUniqUrls (playlistUrl: string) {
db4b15f2 160 const { body } = await doRequest(playlistUrl)
4c280004
C
161
162 if (!body) return []
163
164 const urls = body.split('\n')
165 .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
166 .map(url => {
167 if (url.startsWith('http://') || url.startsWith('https://')) return url
168
169 return `${dirname(playlistUrl)}/${url}`
170 })
171
172 return uniq(urls)
173 }
09209296
C
174}
175
176// ---------------------------------------------------------------------------
177
178export {
179 updateMasterHLSPlaylist,
c6c0fa6c
C
180 updateSha256VODSegments,
181 buildSha256Segment,
ae9bbed4
C
182 downloadPlaylistSegments,
183 updateStreamingPlaylistsInfohashesIfNeeded
09209296
C
184}
185
186// ---------------------------------------------------------------------------
b5b68755
C
187
188function getRangesFromPlaylist (playlistContent: string) {
189 const ranges: { offset: number, length: number }[] = []
190 const lines = playlistContent.split('\n')
191 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
192
193 for (const line of lines) {
194 const captured = regex.exec(line)
195
196 if (captured) {
197 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
198 }
199 }
200
201 return ranges
202}