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