1 import { VideoModel } from '../models/video/video'
2 import { basename, dirname, join } from 'path'
3 import { CONFIG, HLS_STREAMING_PLAYLIST_DIRECTORY, sequelizeTypescript } from '../initializers'
4 import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
5 import { getVideoFileSize } from '../helpers/ffmpeg-utils'
6 import { sha256 } from '../helpers/core-utils'
7 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
8 import { logger } from '../helpers/logger'
9 import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
10 import { generateRandomString } from '../helpers/utils'
11 import { flatten, uniq } from 'lodash'
12 import { VideoFileModel } from '../models/video/video-file'
14 async function updateStreamingPlaylistsInfohashesIfNeeded () {
15 const playlistsToUpdate = await VideoStreamingPlaylistModel.listByIncorrectPeerVersion()
17 // Use separate SQL queries, because we could have many videos to update
18 for (const playlist of playlistsToUpdate) {
19 await sequelizeTypescript.transaction(async t => {
20 const videoFiles = await VideoFileModel.listByStreamingPlaylist(playlist.id, t)
22 playlist.p2pMediaLoaderInfohashes = await VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlist.playlistUrl, videoFiles)
23 await playlist.save({ transaction: t })
28 async function updateMasterHLSPlaylist (video: VideoModel) {
29 const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
30 const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
31 const masterPlaylistPath = join(directory, VideoStreamingPlaylistModel.getMasterHlsPlaylistFilename())
33 for (const file of video.VideoFiles) {
34 // If we did not generated a playlist for this resolution, skip
35 const filePlaylistPath = join(directory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
36 if (await pathExists(filePlaylistPath) === false) continue
38 const videoFilePath = video.getVideoFilePath(file)
40 const size = await getVideoFileSize(videoFilePath)
42 const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
43 const resolution = `RESOLUTION=${size.width}x${size.height}`
45 let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
46 if (file.fps) line += ',FRAME-RATE=' + file.fps
48 masterPlaylists.push(line)
49 masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
52 await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
55 async function updateSha256Segments (video: VideoModel) {
56 const json: { [filename: string]: { [range: string]: string } } = {}
58 const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
60 // For all the resolutions available for this video
61 for (const file of video.VideoFiles) {
62 const rangeHashes: { [range: string]: string } = {}
64 const videoPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution))
65 const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
67 // Maybe the playlist is not generated for this resolution yet
68 if (!await pathExists(playlistPath)) continue
70 const playlistContent = await readFile(playlistPath)
71 const ranges = getRangesFromPlaylist(playlistContent.toString())
73 const fd = await open(videoPath, 'r')
74 for (const range of ranges) {
75 const buf = Buffer.alloc(range.length)
76 await read(fd, buf, 0, range.length, range.offset)
78 rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
82 const videoFilename = VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution)
83 json[videoFilename] = rangeHashes
86 const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
87 await outputJSON(outputPath, json)
90 function getRangesFromPlaylist (playlistContent: string) {
91 const ranges: { offset: number, length: number }[] = []
92 const lines = playlistContent.split('\n')
93 const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
95 for (const line of lines) {
96 const captured = regex.exec(line)
99 ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
106 function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
109 logger.info('Importing HLS playlist %s', playlistUrl)
111 return new Promise<string>(async (res, rej) => {
112 const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
114 await ensureDir(tmpDirectory)
116 timer = setTimeout(() => {
117 deleteTmpDirectory(tmpDirectory)
119 return rej(new Error('HLS download timeout.'))
123 // Fetch master playlist
124 const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
126 const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
127 const fileUrls = uniq(flatten(await Promise.all(subRequests)))
129 logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
131 for (const fileUrl of fileUrls) {
132 const destPath = join(tmpDirectory, basename(fileUrl))
134 const bodyKBLimit = 10 * 1000 * 1000 // 10GB
135 await doRequestAndSaveToFile({ uri: fileUrl }, destPath, bodyKBLimit)
140 await move(tmpDirectory, destinationDir, { overwrite: true })
144 deleteTmpDirectory(tmpDirectory)
150 function deleteTmpDirectory (directory: string) {
152 .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
155 async function fetchUniqUrls (playlistUrl: string) {
156 const { body } = await doRequest<string>({ uri: playlistUrl })
160 const urls = body.split('\n')
161 .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
163 if (url.startsWith('http://') || url.startsWith('https://')) return url
165 return `${dirname(playlistUrl)}/${url}`
172 // ---------------------------------------------------------------------------
175 updateMasterHLSPlaylist,
176 updateSha256Segments,
177 downloadPlaylistSegments,
178 updateStreamingPlaylistsInfohashesIfNeeded
181 // ---------------------------------------------------------------------------