hls.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { VideoModel } from '../models/video/video'
  2. import { basename, dirname, join } from 'path'
  3. import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants'
  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'
  13. import { CONFIG } from '../initializers/config'
  14. import { sequelizeTypescript } from '../initializers/database'
  15. async function updateStreamingPlaylistsInfohashesIfNeeded () {
  16. 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)
  21. playlist.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlist.playlistUrl, videoFiles)
  22. playlist.p2pMediaLoaderPeerVersion = P2P_MEDIA_LOADER_PEER_VERSION
  23. await playlist.save({ transaction: t })
  24. })
  25. }
  26. }
  27. async function updateMasterHLSPlaylist (video: VideoModel) {
  28. const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
  29. const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ]
  30. const masterPlaylistPath = join(directory, VideoStreamingPlaylistModel.getMasterHlsPlaylistFilename())
  31. for (const file of video.VideoFiles) {
  32. // If we did not generated a playlist for this resolution, skip
  33. const filePlaylistPath = join(directory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
  34. if (await pathExists(filePlaylistPath) === false) continue
  35. const videoFilePath = video.getVideoFilePath(file)
  36. const size = await getVideoFileSize(videoFilePath)
  37. const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file)
  38. const resolution = `RESOLUTION=${size.width}x${size.height}`
  39. let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}`
  40. if (file.fps) line += ',FRAME-RATE=' + file.fps
  41. masterPlaylists.push(line)
  42. masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
  43. }
  44. await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
  45. }
  46. async function updateSha256Segments (video: VideoModel) {
  47. const json: { [filename: string]: { [range: string]: string } } = {}
  48. const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
  49. // For all the resolutions available for this video
  50. for (const file of video.VideoFiles) {
  51. const rangeHashes: { [range: string]: string } = {}
  52. const videoPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution))
  53. const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
  54. // Maybe the playlist is not generated for this resolution yet
  55. if (!await pathExists(playlistPath)) continue
  56. const playlistContent = await readFile(playlistPath)
  57. const ranges = getRangesFromPlaylist(playlistContent.toString())
  58. const fd = await open(videoPath, 'r')
  59. for (const range of ranges) {
  60. const buf = Buffer.alloc(range.length)
  61. await read(fd, buf, 0, range.length, range.offset)
  62. rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
  63. }
  64. await close(fd)
  65. const videoFilename = VideoStreamingPlaylistModel.getHlsVideoName(video.uuid, file.resolution)
  66. json[videoFilename] = rangeHashes
  67. }
  68. const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
  69. await outputJSON(outputPath, json)
  70. }
  71. function getRangesFromPlaylist (playlistContent: string) {
  72. const ranges: { offset: number, length: number }[] = []
  73. const lines = playlistContent.split('\n')
  74. const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
  75. for (const line of lines) {
  76. const captured = regex.exec(line)
  77. if (captured) {
  78. ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
  79. }
  80. }
  81. return ranges
  82. }
  83. function downloadPlaylistSegments (playlistUrl: string, destinationDir: string, timeout: number) {
  84. let timer
  85. logger.info('Importing HLS playlist %s', playlistUrl)
  86. return new Promise<string>(async (res, rej) => {
  87. const tmpDirectory = join(CONFIG.STORAGE.TMP_DIR, await generateRandomString(10))
  88. await ensureDir(tmpDirectory)
  89. timer = setTimeout(() => {
  90. deleteTmpDirectory(tmpDirectory)
  91. return rej(new Error('HLS download timeout.'))
  92. }, timeout)
  93. try {
  94. // Fetch master playlist
  95. const subPlaylistUrls = await fetchUniqUrls(playlistUrl)
  96. const subRequests = subPlaylistUrls.map(u => fetchUniqUrls(u))
  97. const fileUrls = uniq(flatten(await Promise.all(subRequests)))
  98. logger.debug('Will download %d HLS files.', fileUrls.length, { fileUrls })
  99. for (const fileUrl of fileUrls) {
  100. const destPath = join(tmpDirectory, basename(fileUrl))
  101. const bodyKBLimit = 10 * 1000 * 1000 // 10GB
  102. await doRequestAndSaveToFile({ uri: fileUrl }, destPath, bodyKBLimit)
  103. }
  104. clearTimeout(timer)
  105. await move(tmpDirectory, destinationDir, { overwrite: true })
  106. return res()
  107. } catch (err) {
  108. deleteTmpDirectory(tmpDirectory)
  109. return rej(err)
  110. }
  111. })
  112. function deleteTmpDirectory (directory: string) {
  113. remove(directory)
  114. .catch(err => logger.error('Cannot delete path on HLS download error.', { err }))
  115. }
  116. async function fetchUniqUrls (playlistUrl: string) {
  117. const { body } = await doRequest<string>({ uri: playlistUrl })
  118. if (!body) return []
  119. const urls = body.split('\n')
  120. .filter(line => line.endsWith('.m3u8') || line.endsWith('.mp4'))
  121. .map(url => {
  122. if (url.startsWith('http://') || url.startsWith('https://')) return url
  123. return `${dirname(playlistUrl)}/${url}`
  124. })
  125. return uniq(urls)
  126. }
  127. }
  128. // ---------------------------------------------------------------------------
  129. export {
  130. updateMasterHLSPlaylist,
  131. updateSha256Segments,
  132. downloadPlaylistSegments,
  133. updateStreamingPlaylistsInfohashesIfNeeded
  134. }
  135. // ---------------------------------------------------------------------------