hls.ts 6.7 KB

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