-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideojs-whep-viewer.js
More file actions
187 lines (158 loc) · 5.09 KB
/
videojs-whep-viewer.js
File metadata and controls
187 lines (158 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import videojs from 'video.js'
import { WHEPClient } from 'whip/whep'
const Plugin = videojs.getPlugin('plugin')
const ModalDialog = videojs.getComponent('ModalDialog')
const bitsUnitsStorage = ['bps', 'kbps', 'mbps', 'gbps']
const labelsByNumLayers = {
2: ['High', 'Low'],
3: ['High', 'Medium', 'Low'],
4: (activeLayers) => activeLayers.map((layer) => {
return formatBitsRecursive(layer.bitrate)
})
}
export default class MillicastWhepPlugin extends Plugin {
constructor (player, options) {
super(player, options)
// Work around to avoid using src method instead of srcObject
player.src = () => {}
this.url = options.url
this.modal = new ModalDialog(player, {
temporary: false,
label: 'Offline',
uncloseable: true
})
player.addChild(this.modal)
if (!this.url) {
const modalContent = document.createElement('h2')
modalContent.innerHTML = 'No Whep URL provided, use whepUrl query param'
this.modal.content(modalContent)
this.modal.open()
return
}
this.vid = player.tech().el()
player.play = () => {
this.vid.play()
}
this.pause = () => {
this.vid.pause()
}
videojs.log('Before WHEP connection')
// Start publishing
this.millicastView(player, options)
if (player.videoJsResolutionSwitcher) {
player.videoJsResolutionSwitcher({
ui: true,
default: 'auto',
customSourcePicker: (p) => { return p },
dynamicLabel: true
})
}
this.auto = {
src: this.url,
type: 'video/mp4',
label: 'Auto',
res: 'auto'
}
player.on('resolutionchange', () => {
const encodingId = player.currentResolution().sources[0].res
this.selectLayer(encodingId)
})
}
millicastView = async (player, options) => {
// Create whip client
this.whep = new WHEPClient()
try {
this.stream = new MediaStream()
this.vid.srcObject = this.stream
// Create Peer Connection
this.pc = new RTCPeerConnection()
// Add audio and video transceivers to the Peer Connection
this.pc.addTransceiver('video', {
direction: 'recvonly'
})
this.pc.addTransceiver('audio', {
direction: 'recvonly'
})
await this.whep.view(this.pc, options.url)
this.modal.close()
// Add tracks transceiver receiver tracks to our Media Stream object
this.pc.getReceivers().forEach((r) => {
this.stream.addTrack(r.track)
})
player.play()
// Listen for whep events
await this.waitForEventSource().then(eventSource => {
eventSource.addEventListener('layers', (event) => {
const layerEvent = JSON.parse(event.data).medias[0]
const currentActiveLayers = layerEvent.active
this.layers = layerEvent.layers
if (player.videoJsResolutionSwitcher) {
this.updateQualityMenu(currentActiveLayers)
}
})
})
} catch (error) {
const modalContent = document.createElement('h2')
modalContent.innerHTML = error
this.modal.content(modalContent)
this.modal.open()
player.pause()
// Add retries every 2 seconds if connection fails
setTimeout(() => {
this.millicastView(player, options)
}, 2000)
}
}
updateQualityMenu (activeLayers) {
const qualityMenu = document.querySelector('[aria-label="Quality"] button')
const length = activeLayers.length
if (length <= 1) {
qualityMenu.disabled = true
qualityMenu.style.opacity = 0.5
qualityMenu.title = 'Quality disabled'
} else {
qualityMenu.disabled = false
qualityMenu.style.opacity = 1
qualityMenu.title = 'Quality'
const labels = length > 3 ? labelsByNumLayers[4](activeLayers) : labelsByNumLayers[length]
const sources = [
this.auto,
...activeLayers.map(({ id }, index) => ({
src: this.url,
type: 'video/mp4',
label: labels[index],
res: id
}))
]
if (this.player.videoJsResolutionSwitcher) {
this.player.updateSrc(sources)
}
}
}
selectLayer = async (encodingId) => {
// await this.whep.unselectLayer()
const layerSelected = encodingId === 'auto' ? {} : this.layers.filter(l => l.encodingId === encodingId)[0]
await this.whep.selectLayer(layerSelected)
}
waitForEventSource = async () => {
return new Promise((resolve) => {
if (this.whep.eventSource) {
resolve(this.whep.eventSource)
} else {
setTimeout(() => {
resolve(this.waitForEventSource())
}, 1000)
}
})
}
}
const formatBitsRecursive = (value, unitsStoragePosition = 0) => {
const newValue = value / 1000
if ((newValue < 1) || (newValue > 1 && (unitsStoragePosition + 1) > bitsUnitsStorage.length)) {
return `${Math.round(value * 100) / 100} ${bitsUnitsStorage[unitsStoragePosition]}`
} else if (newValue > 1) {
return formatBitsRecursive(newValue, unitsStoragePosition + 1)
}
}
// All that's left is to register the plugin with Video.js:
videojs.registerPlugin('millicastViewer', MillicastWhepPlugin)