]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/videos/live.ts
65942db0a1dda5b67ac4755ecefe2ebc1868de24
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / videos / live.ts
1 import * as ffmpeg from 'fluent-ffmpeg'
2 import { LiveVideoCreate, LiveVideoUpdate, VideoDetails, VideoState } from '@shared/models'
3 import { buildAbsoluteFixturePath, wait } from '../miscs/miscs'
4 import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests'
5 import { getVideoWithToken } from './videos'
6 import { omit } from 'lodash'
7
8 function getLive (url: string, token: string, videoId: number | string, statusCodeExpected = 200) {
9 const path = '/api/v1/videos/live'
10
11 return makeGetRequest({
12 url,
13 token,
14 path: path + '/' + videoId,
15 statusCodeExpected
16 })
17 }
18
19 function updateLive (url: string, token: string, videoId: number | string, fields: LiveVideoUpdate, statusCodeExpected = 204) {
20 const path = '/api/v1/videos/live'
21
22 return makePutBodyRequest({
23 url,
24 token,
25 path: path + '/' + videoId,
26 fields,
27 statusCodeExpected
28 })
29 }
30
31 function createLive (url: string, token: string, fields: LiveVideoCreate, statusCodeExpected = 200) {
32 const path = '/api/v1/videos/live'
33
34 const attaches: any = {}
35 if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile
36 if (fields.previewfile) attaches.previewfile = fields.previewfile
37
38 const updatedFields = omit(fields, 'thumbnailfile', 'previewfile')
39
40 return makeUploadRequest({
41 url,
42 path,
43 token,
44 attaches,
45 fields: updatedFields,
46 statusCodeExpected
47 })
48 }
49
50 function sendRTMPStream (rtmpBaseUrl: string, streamKey: string) {
51 const fixture = buildAbsoluteFixturePath('video_short.mp4')
52
53 const command = ffmpeg(fixture)
54 command.inputOption('-stream_loop -1')
55 command.inputOption('-re')
56
57 command.outputOption('-c copy')
58 command.outputOption('-f flv')
59
60 const rtmpUrl = rtmpBaseUrl + '/' + streamKey
61 command.output(rtmpUrl)
62
63 command.on('error', err => {
64 if (err?.message?.includes('Exiting normally')) return
65
66 console.error('Cannot send RTMP stream.', { err })
67 })
68
69 if (process.env.DEBUG) {
70 command.on('stderr', data => console.log(data))
71 }
72
73 command.run()
74
75 return command
76 }
77
78 async function stopFfmpeg (command: ffmpeg.FfmpegCommand) {
79 command.kill('SIGINT')
80
81 await wait(500)
82 }
83
84 async function waitUntilLiveStarts (url: string, token: string, videoId: number | string) {
85 let video: VideoDetails
86
87 do {
88 const res = await getVideoWithToken(url, token, videoId)
89 video = res.body
90
91 await wait(500)
92 } while (video.state.id === VideoState.WAITING_FOR_LIVE)
93 }
94
95 // ---------------------------------------------------------------------------
96
97 export {
98 getLive,
99 updateLive,
100 waitUntilLiveStarts,
101 createLive,
102 stopFfmpeg,
103 sendRTMPStream
104 }