live.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
  2. import { expect } from 'chai'
  3. import * as ffmpeg from 'fluent-ffmpeg'
  4. import { pathExists, readdir } from 'fs-extra'
  5. import { omit } from 'lodash'
  6. import { join } from 'path'
  7. import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoDetails, VideoState } from '@shared/models'
  8. import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
  9. import { buildAbsoluteFixturePath, buildServerDirectory, wait } from '../miscs/miscs'
  10. import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests'
  11. import { ServerInfo, waitUntilLog } from '../server/servers'
  12. import { getVideoWithToken } from './videos'
  13. function getLive (url: string, token: string, videoId: number | string, statusCodeExpected = HttpStatusCode.OK_200) {
  14. const path = '/api/v1/videos/live'
  15. return makeGetRequest({
  16. url,
  17. token,
  18. path: path + '/' + videoId,
  19. statusCodeExpected
  20. })
  21. }
  22. function updateLive (
  23. url: string,
  24. token: string,
  25. videoId: number | string,
  26. fields: LiveVideoUpdate,
  27. statusCodeExpected = HttpStatusCode.NO_CONTENT_204
  28. ) {
  29. const path = '/api/v1/videos/live'
  30. return makePutBodyRequest({
  31. url,
  32. token,
  33. path: path + '/' + videoId,
  34. fields,
  35. statusCodeExpected
  36. })
  37. }
  38. function createLive (url: string, token: string, fields: LiveVideoCreate, statusCodeExpected = HttpStatusCode.OK_200) {
  39. const path = '/api/v1/videos/live'
  40. const attaches: any = {}
  41. if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile
  42. if (fields.previewfile) attaches.previewfile = fields.previewfile
  43. const updatedFields = omit(fields, 'thumbnailfile', 'previewfile')
  44. return makeUploadRequest({
  45. url,
  46. path,
  47. token,
  48. attaches,
  49. fields: updatedFields,
  50. statusCodeExpected
  51. })
  52. }
  53. async function sendRTMPStreamInVideo (url: string, token: string, videoId: number | string, fixtureName?: string) {
  54. const res = await getLive(url, token, videoId)
  55. const videoLive = res.body as LiveVideo
  56. return sendRTMPStream(videoLive.rtmpUrl, videoLive.streamKey, fixtureName)
  57. }
  58. function sendRTMPStream (rtmpBaseUrl: string, streamKey: string, fixtureName = 'video_short.mp4') {
  59. const fixture = buildAbsoluteFixturePath(fixtureName)
  60. const command = ffmpeg(fixture)
  61. command.inputOption('-stream_loop -1')
  62. command.inputOption('-re')
  63. command.outputOption('-c:v libx264')
  64. command.outputOption('-g 50')
  65. command.outputOption('-keyint_min 2')
  66. command.outputOption('-r 60')
  67. command.outputOption('-f flv')
  68. const rtmpUrl = rtmpBaseUrl + '/' + streamKey
  69. command.output(rtmpUrl)
  70. command.on('error', err => {
  71. if (err?.message?.includes('Exiting normally')) return
  72. if (process.env.DEBUG) console.error(err)
  73. })
  74. if (process.env.DEBUG) {
  75. command.on('stderr', data => console.log(data))
  76. }
  77. command.run()
  78. return command
  79. }
  80. function waitFfmpegUntilError (command: ffmpeg.FfmpegCommand, successAfterMS = 10000) {
  81. return new Promise((res, rej) => {
  82. command.on('error', err => {
  83. return rej(err)
  84. })
  85. setTimeout(() => {
  86. res()
  87. }, successAfterMS)
  88. })
  89. }
  90. async function runAndTestFfmpegStreamError (url: string, token: string, videoId: number | string, shouldHaveError: boolean) {
  91. const command = await sendRTMPStreamInVideo(url, token, videoId)
  92. return testFfmpegStreamError(command, shouldHaveError)
  93. }
  94. async function testFfmpegStreamError (command: ffmpeg.FfmpegCommand, shouldHaveError: boolean) {
  95. let error: Error
  96. try {
  97. await waitFfmpegUntilError(command, 25000)
  98. } catch (err) {
  99. error = err
  100. }
  101. await stopFfmpeg(command)
  102. if (shouldHaveError && !error) throw new Error('Ffmpeg did not have an error')
  103. if (!shouldHaveError && error) throw error
  104. }
  105. async function stopFfmpeg (command: ffmpeg.FfmpegCommand) {
  106. command.kill('SIGINT')
  107. await wait(500)
  108. }
  109. function waitUntilLivePublished (url: string, token: string, videoId: number | string) {
  110. return waitUntilLiveState(url, token, videoId, VideoState.PUBLISHED)
  111. }
  112. function waitUntilLiveWaiting (url: string, token: string, videoId: number | string) {
  113. return waitUntilLiveState(url, token, videoId, VideoState.WAITING_FOR_LIVE)
  114. }
  115. function waitUntilLiveEnded (url: string, token: string, videoId: number | string) {
  116. return waitUntilLiveState(url, token, videoId, VideoState.LIVE_ENDED)
  117. }
  118. function waitUntilLiveSegmentGeneration (server: ServerInfo, videoUUID: string, resolutionNum: number, segmentNum: number) {
  119. const segmentName = `${resolutionNum}-00000${segmentNum}.ts`
  120. return waitUntilLog(server, `${videoUUID}/${segmentName}`, 2, false)
  121. }
  122. async function waitUntilLiveState (url: string, token: string, videoId: number | string, state: VideoState) {
  123. let video: VideoDetails
  124. do {
  125. const res = await getVideoWithToken(url, token, videoId)
  126. video = res.body
  127. await wait(500)
  128. } while (video.state.id !== state)
  129. }
  130. async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resolutions: number[] = []) {
  131. const basePath = buildServerDirectory(server, 'streaming-playlists')
  132. const hlsPath = join(basePath, 'hls', videoUUID)
  133. if (resolutions.length === 0) {
  134. const result = await pathExists(hlsPath)
  135. expect(result).to.be.false
  136. return
  137. }
  138. const files = await readdir(hlsPath)
  139. // fragmented file and playlist per resolution + master playlist + segments sha256 json file
  140. expect(files).to.have.lengthOf(resolutions.length * 2 + 2)
  141. for (const resolution of resolutions) {
  142. expect(files).to.contain(`${videoUUID}-${resolution}-fragmented.mp4`)
  143. expect(files).to.contain(`${resolution}.m3u8`)
  144. }
  145. expect(files).to.contain('master.m3u8')
  146. expect(files).to.contain('segments-sha256.json')
  147. }
  148. async function getPlaylistsCount (server: ServerInfo, videoUUID: string) {
  149. const basePath = buildServerDirectory(server, 'streaming-playlists')
  150. const hlsPath = join(basePath, 'hls', videoUUID)
  151. const files = await readdir(hlsPath)
  152. return files.filter(f => f.endsWith('.m3u8')).length
  153. }
  154. // ---------------------------------------------------------------------------
  155. export {
  156. getLive,
  157. getPlaylistsCount,
  158. waitUntilLivePublished,
  159. updateLive,
  160. createLive,
  161. runAndTestFfmpegStreamError,
  162. checkLiveCleanup,
  163. waitUntilLiveSegmentGeneration,
  164. stopFfmpeg,
  165. waitUntilLiveWaiting,
  166. sendRTMPStreamInVideo,
  167. waitUntilLiveEnded,
  168. waitFfmpegUntilError,
  169. sendRTMPStream,
  170. testFfmpegStreamError
  171. }