2
1

hls.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, writeFile } from 'fs-extra'
  2. import { flatten, uniq } from 'lodash'
  3. import { basename, dirname, join } from 'path'
  4. import { MVideoWithFile } from '@server/types/models'
  5. import { sha256 } from '../helpers/core-utils'
  6. import { getAudioStreamCodec, getVideoStreamCodec, getVideoStreamSize } from '../helpers/ffprobe-utils'
  7. import { logger } from '../helpers/logger'
  8. import { doRequest, doRequestAndSaveToFile } from '../helpers/requests'
  9. import { generateRandomString } from '../helpers/utils'
  10. import { CONFIG } from '../initializers/config'
  11. import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants'
  12. import { sequelizeTypescript } from '../initializers/database'
  13. import { VideoFileModel } from '../models/video/video-file'
  14. import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
  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 getVideoStreamSize(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. const videoCodec = await getVideoStreamCodec(videoFilePath)
  44. line += `,CODECS="${videoCodec}`
  45. const audioCodec = await getAudioStreamCodec(videoFilePath)
  46. if (audioCodec) line += `,${audioCodec}`
  47. line += '"'
  48. masterPlaylists.push(line)
  49. masterPlaylists.push(VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
  50. }
  51. await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n')
  52. }
  53. async function updateSha256VODSegments (video: MVideoWithFile) {
  54. const json: { [filename: string]: { [range: string]: string } } = {}
  55. const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)
  56. const hlsPlaylist = video.getHLSPlaylist()
  57. // For all the resolutions available for this video
  58. for (const file of hlsPlaylist.VideoFiles) {
  59. const rangeHashes: { [range: string]: string } = {}
  60. const videoPath = getVideoFilePath(hlsPlaylist, file)
  61. const playlistPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsPlaylistFilename(file.resolution))
  62. // Maybe the playlist is not generated for this resolution yet
  63. if (!await pathExists(playlistPath)) continue
  64. const playlistContent = await readFile(playlistPath)
  65. const ranges = getRangesFromPlaylist(playlistContent.toString())
  66. const fd = await open(videoPath, 'r')
  67. for (const range of ranges) {
  68. const buf = Buffer.alloc(range.length)
  69. await read(fd, buf, 0, range.length, range.offset)
  70. rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf)
  71. }
  72. await close(fd)
  73. const videoFilename = getVideoFilename(hlsPlaylist, file)
  74. json[videoFilename] = rangeHashes
  75. }
  76. const outputPath = join(playlistDirectory, VideoStreamingPlaylistModel.getHlsSha256SegmentsFilename())
  77. await outputJSON(outputPath, json)
  78. }
  79. async function buildSha256Segment (segmentPath: string) {
  80. const buf = await readFile(segmentPath)
  81. return sha256(buf)
  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. updateSha256VODSegments,
  132. buildSha256Segment,
  133. downloadPlaylistSegments,
  134. updateStreamingPlaylistsInfohashesIfNeeded
  135. }
  136. // ---------------------------------------------------------------------------
  137. function getRangesFromPlaylist (playlistContent: string) {
  138. const ranges: { offset: number, length: number }[] = []
  139. const lines = playlistContent.split('\n')
  140. const regex = /^#EXT-X-BYTERANGE:(\d+)@(\d+)$/
  141. for (const line of lines) {
  142. const captured = regex.exec(line)
  143. if (captured) {
  144. ranges.push({ length: parseInt(captured[1], 10), offset: parseInt(captured[2], 10) })
  145. }
  146. }
  147. return ranges
  148. }