├── .formatter.exs
├── .gitignore
├── LICENSE
├── README.md
├── assets
├── index.js
├── player.js
└── publisher.js
├── lib
└── live_ex_webrtc
│ ├── core_components.ex
│ ├── player.ex
│ └── publisher.ex
├── mix.exs
├── mix.lock
├── package.json
└── test
├── live_ex_webrtc_test.exs
└── test_helper.exs
/.formatter.exs:
--------------------------------------------------------------------------------
1 | # Used by "mix format"
2 | [
3 | import_deps: [:phoenix],
4 | plugins: [Phoenix.LiveView.HTMLFormatter],
5 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
6 | ]
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # The directory Mix will write compiled artifacts to.
2 | /_build/
3 |
4 | # If you run "mix test --cover", coverage assets end up here.
5 | /cover/
6 |
7 | # The directory Mix downloads your dependencies sources to.
8 | /deps/
9 |
10 | # Where third-party dependencies like ExDoc output generated docs.
11 | /doc/
12 |
13 | # Ignore .fetch files in case you like to edit your project deps locally.
14 | /.fetch
15 |
16 | # If the VM crashes, it generates a dump, let's ignore it too.
17 | erl_crash.dump
18 |
19 | # Also ignore archive artifacts (built via "mix archive.build").
20 | *.ez
21 |
22 | # Ignore package tarball (built via "mix hex.build").
23 | live_ex_webrtc-*.tar
24 |
25 | # Temporary files, for example, from tests.
26 | /tmp/
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2024 Elixir WebRTC Developers
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LiveExWebRTC
2 |
3 | [](https://hex.pm/packages/live_ex_webrtc)
4 | [](https://hexdocs.pm/live_ex_webrtc)
5 |
6 | Phoenix Live Components for [Elixir WebRTC](https://github.com/elixir-webrtc/ex_webrtc).
7 |
8 | ## Installation
9 |
10 | In your `mix.exs`:
11 |
12 | ```elixir
13 | def deps do
14 | [
15 | {:live_ex_webrtc, "~> 0.8.0"}
16 | ]
17 | end
18 | ```
19 |
20 | In your `tailwind.config.js`
21 |
22 | ```js
23 | module.exports = {
24 | content: [
25 | "../deps/live_ex_webrtc/**/*.*ex" // ADD THIS LINE
26 | ]
27 | }
28 | ```
29 |
30 | ## Usage
31 |
32 | `LiveExWebRTC` comes with two `Phoenix.LiveView`s:
33 | * `LiveExWebRTC.Publisher` - sends audio and video via WebRTC from a web browser to a Phoenix app (browser publishes)
34 | * `LiveExWebRTC.Player` - sends audio and video via WebRTC from a Phoenix app to a web browser and plays it in the HTMLVideoElement (browser subscribes)
35 |
36 | See module docs and [live_broadcaster](https://github.com/elixir-webrtc/live_broadcaster) for more.
37 |
38 | ## Local development
39 |
40 | For local development:
41 | * include `live_ex_webrtc` in your `mix.exs` via `path`
42 | * modify `NODE_PATH` env variable in your esbuild configuration, which is located in `config.exs` - this will allow for importing javascript hooks from `live_ex_webrtc`.
43 |
44 | For example:
45 |
46 | ```elixir
47 | config :esbuild,
48 | # ...
49 | default: [
50 | # ...
51 | env: %{
52 | "NODE_PATH" => "#{Path.expand("../deps", __DIR__)}:/path/to/parent/dir/of/live_ex_webrtc"
53 | }
54 | ]
55 | ```
56 |
57 | * modify `content` in `tailwind.config.js` - this will compile tailwind classes used in live components.
58 |
59 | For example:
60 |
61 | ```js
62 | module.exports = {
63 | content: [
64 | // ...
65 | "../deps/**/*.ex"
66 | ]
67 | }
68 | ```
69 |
70 | > #### Important {: .info}
71 | > Separate paths with `:` on MacOS/Linux and with `;` on Windows.
72 |
73 | > #### Important {: .info}
74 | > Specify path to live_ex_webrtc's parent directory.
75 |
--------------------------------------------------------------------------------
/assets/index.js:
--------------------------------------------------------------------------------
1 | import { createPublisherHook } from "./publisher.js";
2 | import { createPlayerHook } from "./player.js";
3 |
4 | export { createPublisherHook, createPlayerHook };
5 |
--------------------------------------------------------------------------------
/assets/player.js:
--------------------------------------------------------------------------------
1 | export function createPlayerHook(iceServers = []) {
2 | return {
3 | async mounted() {
4 | const view = this;
5 |
6 | view.handleEvent(
7 | `connect-${view.el.id}`,
8 | async () => await view.connect(view)
9 | );
10 |
11 | const eventName = "answer" + "-" + view.el.id;
12 | view.handleEvent(eventName, async (answer) => {
13 | if (view.pc) {
14 | await view.pc.setRemoteDescription(answer);
15 | }
16 | });
17 |
18 | view.videoQuality = document.getElementById("lexp-video-quality");
19 | view.videoQuality.onchange = () => {
20 | view.pushEventTo(view.el, "layer", view.videoQuality.value);
21 | };
22 | },
23 |
24 | async connect(view) {
25 | view.el.srcObject = undefined;
26 | view.pc = new RTCPeerConnection({ iceServers: iceServers });
27 | view.el.play();
28 |
29 | view.pc.onicecandidate = (ev) => {
30 | view.pushEventTo(view.el, "ice", JSON.stringify(ev.candidate));
31 | };
32 |
33 | view.pc.ontrack = (ev) => {
34 | if (!view.el.srcObject) {
35 | view.el.srcObject = ev.streams[0];
36 | }
37 | };
38 | view.pc.addTransceiver("audio", { direction: "recvonly" });
39 | view.pc.addTransceiver("video", { direction: "recvonly" });
40 |
41 | const offer = await view.pc.createOffer();
42 | await view.pc.setLocalDescription(offer);
43 |
44 | view.pushEventTo(view.el, "offer", offer);
45 | },
46 | };
47 | }
48 |
--------------------------------------------------------------------------------
/assets/publisher.js:
--------------------------------------------------------------------------------
1 | export function createPublisherHook(iceServers = []) {
2 | return {
3 | async mounted() {
4 | const view = this;
5 |
6 | view.handleEvent("start-streaming", () => view.startStreaming(view));
7 | view.handleEvent("stop-streaming", () => view.stopStreaming(view));
8 |
9 | view.audioDevices = document.getElementById("lex-audio-devices");
10 | view.videoDevices = document.getElementById("lex-video-devices");
11 |
12 | view.echoCancellation = document.getElementById("lex-echo-cancellation");
13 | view.autoGainControl = document.getElementById("lex-auto-gain-control");
14 | view.noiseSuppression = document.getElementById("lex-noise-suppression");
15 |
16 | view.width = document.getElementById("lex-width");
17 | view.height = document.getElementById("lex-height");
18 | view.fps = document.getElementById("lex-fps");
19 | view.bitrate = document.getElementById("lex-bitrate");
20 |
21 | view.recordStream = document.getElementById("lex-record-stream");
22 |
23 | view.previewPlayer = document.getElementById("lex-preview-player");
24 |
25 | view.audioBitrate = document.getElementById("lex-audio-bitrate");
26 | view.videoBitrate = document.getElementById("lex-video-bitrate");
27 | view.packetLoss = document.getElementById("lex-packet-loss");
28 | view.statusStarted = document.getElementById("lex-status-started");
29 | view.statusStopped = document.getElementById("lex-status-stopped");
30 | view.time = document.getElementById("lex-time");
31 |
32 | view.button = document.getElementById("lex-button");
33 | view.applyButton = document.getElementById("lex-apply-button");
34 |
35 | view.simulcast = document.getElementById("lex-simulcast");
36 |
37 | view.audioDevices.onchange = function () {
38 | view.setupStream(view);
39 | };
40 |
41 | view.videoDevices.onchange = function () {
42 | view.setupStream(view);
43 | };
44 |
45 | view.applyButton.onclick = function () {
46 | view.setupStream(view);
47 | };
48 |
49 | // handle remote events
50 | view.handleEvent(`answer-${view.el.id}`, async (answer) => {
51 | if (view.pc) {
52 | await view.pc.setRemoteDescription(answer);
53 | } else {
54 | console.warn("Received SDP cnswer but there is no PC. Ignoring.");
55 | }
56 | });
57 |
58 | view.handleEvent(`ice-${view.el.id}`, async (cand) => {
59 | if (view.pc) {
60 | await view.pc.addIceCandidate(JSON.parse(cand));
61 | } else {
62 | console.warn("Received ICE candidate but there is no PC. Ignoring.");
63 | }
64 | });
65 |
66 | try {
67 | await view.findDevices(view);
68 | try {
69 | await view.setupStream(view);
70 | view.button.disabled = false;
71 | view.applyButton.disabled = false;
72 | } catch (error) {
73 | console.error("Couldn't setup stream, reason:", error.stack);
74 | }
75 | } catch (error) {
76 | console.error(
77 | "Couldn't find audio and/or video devices, reason: ",
78 | error.stack
79 | );
80 | }
81 | },
82 |
83 | disableControls(view) {
84 | view.audioDevices.disabled = true;
85 | view.videoDevices.disabled = true;
86 | view.echoCancellation.disabled = true;
87 | view.autoGainControl.disabled = true;
88 | view.noiseSuppression.disabled = true;
89 | view.width.disabled = true;
90 | view.height.disabled = true;
91 | view.fps.disabled = true;
92 | view.bitrate.disabled = true;
93 | view.simulcast.disabled = true;
94 | view.applyButton.disabled = true;
95 | // Button present only when Recorder is used
96 | if (view.recordStream) view.recordStream.disabled = true;
97 | },
98 |
99 | enableControls(view) {
100 | view.audioDevices.disabled = false;
101 | view.videoDevices.disabled = false;
102 | view.echoCancellation.disabled = false;
103 | view.autoGainControl.disabled = false;
104 | view.noiseSuppression.disabled = false;
105 | view.width.disabled = false;
106 | view.height.disabled = false;
107 | view.fps.disabled = false;
108 | view.bitrate.disabled = false;
109 | view.simulcast.disabled = false;
110 | view.applyButton.disabled = false;
111 | // See above
112 | if (view.recordStream) view.recordStream.disabled = false;
113 | },
114 |
115 | async findDevices(view) {
116 | // ask for permissions
117 | view.localStream = await navigator.mediaDevices.getUserMedia({
118 | video: true,
119 | audio: true,
120 | });
121 |
122 | console.log(`Obtained stream with id: ${view.localStream.id}`);
123 |
124 | // enumerate devices
125 | const devices = await navigator.mediaDevices.enumerateDevices();
126 | devices.forEach((device) => {
127 | if (device.kind === "videoinput") {
128 | view.videoDevices.options[view.videoDevices.options.length] =
129 | new Option(device.label, device.deviceId);
130 | } else if (device.kind === "audioinput") {
131 | view.audioDevices.options[view.audioDevices.options.length] =
132 | new Option(device.label, device.deviceId);
133 | }
134 | });
135 |
136 | // for some reasons, firefox loses labels after closing the stream
137 | // so we close it after filling audio/video devices selects
138 | view.closeStream(view);
139 | },
140 |
141 | closeStream(view) {
142 | if (view.localStream != undefined) {
143 | console.log(`Closing stream with id: ${view.localStream.id}`);
144 | view.localStream.getTracks().forEach((track) => track.stop());
145 | view.localStream = undefined;
146 | }
147 | },
148 |
149 | async setupStream(view) {
150 | if (view.localStream != undefined) {
151 | view.closeStream(view);
152 | }
153 |
154 | const videoDevice = view.videoDevices.value;
155 | const audioDevice = view.audioDevices.value;
156 |
157 | console.log(
158 | `Setting up stream: audioDevice: ${audioDevice}, videoDevice: ${videoDevice}`
159 | );
160 |
161 | view.localStream = await navigator.mediaDevices.getUserMedia({
162 | video: {
163 | deviceId: { exact: videoDevice },
164 | width: view.width.value,
165 | height: view.height.value,
166 | frameRate: view.fps.value,
167 | },
168 | audio: {
169 | deviceId: { exact: audioDevice },
170 | echoCancellation: view.echoCancellation.checked,
171 | autoGainControl: view.autoGainControl.checked,
172 | noiseSuppression: view.noiseSuppression.checked,
173 | },
174 | });
175 |
176 | console.log(`Obtained stream with id: ${view.localStream.id}`);
177 |
178 | view.previewPlayer.srcObject = view.localStream;
179 | },
180 |
181 | async startStreaming(view) {
182 | view.disableControls(view);
183 |
184 | view.pc = new RTCPeerConnection({ iceServers: iceServers });
185 |
186 | // handle local events
187 | view.pc.onconnectionstatechange = () => {
188 | if (view.pc.connectionState === "connected") {
189 | view.startTime = new Date();
190 | view.statusStopped.style.display = "none";
191 | view.statusStarted.style.display = "block";
192 |
193 | view.statsIntervalId = setInterval(async function () {
194 | if (!view.pc) {
195 | clearInterval(view.statsIntervalId);
196 | view.statsIntervalId = undefined;
197 | return;
198 | }
199 |
200 | view.time.innerText = view.toHHMMSS(new Date() - view.startTime);
201 |
202 | const stats = await view.pc.getStats(null);
203 | view.processStats(view, stats);
204 | }, 1000);
205 | } else if (view.pc.connectionState === "failed") {
206 | view.pushEvent("stop-streaming", { reason: "failed" });
207 | view.stopStreaming(view);
208 | }
209 | };
210 |
211 | view.pc.onicecandidate = (ev) => {
212 | view.pushEventTo(view.el, "ice", JSON.stringify(ev.candidate));
213 | };
214 |
215 | view.pc.addTrack(view.localStream.getAudioTracks()[0], view.localStream);
216 |
217 | if (view.simulcast.checked === true) {
218 | view.addSimulcastVideo(view);
219 | } else {
220 | view.addNormalVideo(view);
221 | }
222 |
223 | const offer = await view.pc.createOffer();
224 | await view.pc.setLocalDescription(offer);
225 |
226 | view.pushEventTo(view.el, "offer", offer);
227 | },
228 |
229 | processStats(view, stats) {
230 | let videoBytesSent = 0;
231 | let videoPacketsSent = 0;
232 | let videoNack = 0;
233 | let audioBytesSent = 0;
234 | let audioPacketsSent = 0;
235 | let audioNack = 0;
236 |
237 | let statsTimestamp;
238 | stats.forEach((report) => {
239 | if (!statsTimestamp) statsTimestamp = report.timestamp;
240 |
241 | if (report.type === "outbound-rtp" && report.kind === "video") {
242 | videoBytesSent += report.bytesSent;
243 | videoPacketsSent += report.packetsSent;
244 | videoNack += report.nackCount;
245 | } else if (report.type === "outbound-rtp" && report.kind === "audio") {
246 | audioBytesSent += report.bytesSent;
247 | audioPacketsSent += report.packetsSent;
248 | audioNack += report.nackCount;
249 | }
250 | });
251 |
252 | const timeDiff = (statsTimestamp - view.lastStatsTimestamp) / 1000;
253 |
254 | let bitrate;
255 |
256 | if (!view.lastVideoBytesSent) {
257 | bitrate = (videoBytesSent * 8) / 1000;
258 | } else {
259 | if (timeDiff == 0) {
260 | // this should never happen as we are getting stats every second
261 | bitrate = 0;
262 | } else {
263 | bitrate = ((videoBytesSent - view.lastVideoBytesSent) * 8) / timeDiff;
264 | }
265 | }
266 |
267 | view.videoBitrate.innerText = (bitrate / 1000).toFixed();
268 |
269 | if (!view.lastAudioBytesSent) {
270 | bitrate = (audioBytesSent * 8) / 1000;
271 | } else {
272 | if (timeDiff == 0) {
273 | // this should never happen as we are getting stats every second
274 | bitrate = 0;
275 | } else {
276 | bitrate = ((audioBytesSent - view.lastAudioBytesSent) * 8) / timeDiff;
277 | }
278 | }
279 |
280 | view.audioBitrate.innerText = (bitrate / 1000).toFixed();
281 |
282 | // calculate packet loss
283 | if (!view.lastAudioPacketsSent || !view.lastVideoPacketsSent) {
284 | view.packetLoss.innerText = 0;
285 | } else {
286 | const packetsSent =
287 | videoPacketsSent +
288 | audioPacketsSent -
289 | view.lastAudioPacketsSent -
290 | view.lastVideoPacketsSent;
291 |
292 | const nack =
293 | videoNack + audioNack - view.lastVideoNack - view.lastAudioNack;
294 |
295 | if (packetsSent == 0 || timeDiff == 0) {
296 | view.packetLoss.innerText = 0;
297 | } else {
298 | view.packetLoss.innerText = (
299 | ((nack / packetsSent) * 100) /
300 | timeDiff
301 | ).toFixed(2);
302 | }
303 | }
304 |
305 | view.lastVideoBytesSent = videoBytesSent;
306 | view.lastVideoPacketsSent = videoPacketsSent;
307 | view.lastVideoNack = videoNack;
308 | view.lastAudioBytesSent = audioBytesSent;
309 | view.lastAudioPacketsSent = audioPacketsSent;
310 | view.lastAudioNack = audioNack;
311 | view.lastStatsTimestamp = statsTimestamp;
312 | },
313 |
314 | addSimulcastVideo(view) {
315 | const videoTrack = view.localStream.getVideoTracks()[0];
316 | const settings = videoTrack.getSettings();
317 | const maxTotalBitrate = view.bitrate.value * 1024;
318 |
319 | // This is based on:
320 | // https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/video/config/simulcast.cc;l=79?q=simulcast.cc
321 | let sendEncodings;
322 | if (settings.width >= 960 && settings.height >= 540) {
323 | // we do a very simple calculation: maxTotalBitrate = x + 1/4x + 1/16x
324 | // x - bitrate for base resolution
325 | // 1/4x- bitrate for resolution scaled down by 2 - we decrese total number of pixels by 4 (width/2*height/2)
326 | // 1/16x- bitrate for resolution scaled down by 4 - we decrese total number of pixels by 16 (width/4*height/4)
327 | const maxHBitrate = Math.floor((16 * maxTotalBitrate) / 21);
328 | const maxMBitrate = Math.floor(maxHBitrate / 4);
329 | const maxLBitrate = Math.floor(maxHBitrate / 16);
330 | sendEncodings = [
331 | { rid: "h", maxBitrate: maxHBitrate },
332 | { rid: "m", scaleResolutionDownBy: 2, maxBitrate: maxMBitrate },
333 | { rid: "l", scaleResolutionDownBy: 4, maxBitrate: maxLBitrate },
334 | ];
335 | } else if (settings.width >= 480 && settings.height >= 270) {
336 | // maxTotalBitate = x + 1/4x
337 | const maxHBitrate = Math.floor((4 * maxTotalBitrate) / 5);
338 | const maxMBitrate = Math.floor(maxHBitrate / 4);
339 | sendEncodings = [
340 | { rid: "h", maxBitrate: maxHBitrate },
341 | { rid: "m", scaleResolutionDownBy: 2, maxBitrate: maxMBitrate },
342 | ];
343 | } else {
344 | sendEncodings = [{ rid: "h", maxBitrate: maxTotalBitrate }];
345 | }
346 |
347 | view.pc.addTransceiver(view.localStream.getVideoTracks()[0], {
348 | streams: [view.localStream],
349 | sendEncodings: sendEncodings,
350 | });
351 | },
352 |
353 | addNormalVideo(view) {
354 | view.pc.addTrack(view.localStream.getVideoTracks()[0], view.localStream);
355 |
356 | // set max bitrate
357 | view.pc
358 | .getSenders()
359 | .filter((sender) => sender.track.kind === "video")
360 | .forEach(async (sender) => {
361 | const params = sender.getParameters();
362 | params.encodings[0].maxBitrate = view.bitrate.value * 1024;
363 | await sender.setParameters(params);
364 | });
365 | },
366 |
367 | stopStreaming(view) {
368 | if (view.pc) {
369 | view.pc.close();
370 | view.pc = undefined;
371 | }
372 |
373 | view.resetStats(view);
374 |
375 | view.enableControls(view);
376 | },
377 |
378 | resetStats(view) {
379 | view.startTime = undefined;
380 | view.lastAudioReport = undefined;
381 | view.lastVideoReport = undefined;
382 | view.lastVideoBytesSent = 0;
383 | view.lastVideoPacketsSent = 0;
384 | view.lastVideoNack = 0;
385 | view.lastAudioBytesSent = 0;
386 | view.lastAudioPacketsSent = 0;
387 | view.lastAudioNack = 0;
388 | view.audioBitrate.innerText = 0;
389 | view.videoBitrate.innerText = 0;
390 | view.packetLoss.innerText = 0;
391 | view.time.innerText = "00:00:00";
392 | view.statusStopped.style.display = "block";
393 | view.statusStarted.style.display = "none";
394 | },
395 |
396 | toHHMMSS(milliseconds) {
397 | // Calculate hours
398 | let hours = Math.floor(milliseconds / (1000 * 60 * 60));
399 | // Calculate minutes, subtracting the hours part
400 | let minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60));
401 | // Calculate seconds, subtracting the hours and minutes parts
402 | let seconds = Math.floor((milliseconds % (1000 * 60)) / 1000);
403 |
404 | // Formatting each unit to always have at least two digits
405 | hours = hours < 10 ? "0" + hours : hours;
406 | minutes = minutes < 10 ? "0" + minutes : minutes;
407 | seconds = seconds < 10 ? "0" + seconds : seconds;
408 |
409 | return hours + ":" + minutes + ":" + seconds;
410 | },
411 | };
412 | }
413 |
--------------------------------------------------------------------------------
/lib/live_ex_webrtc/core_components.ex:
--------------------------------------------------------------------------------
1 | defmodule LiveExWebRTC.CoreComponents do
2 | # This code is copied from a newly generated Phoenix project.
3 |
4 | @moduledoc """
5 | Provides core UI components.
6 |
7 | At first glance, this module may seem daunting, but its goal is to provide
8 | core building blocks for your application, such as modals, tables, and
9 | forms. The components consist mostly of markup and are well-documented
10 | with doc strings and declarative assigns. You may customize and style
11 | them in any way you want, based on your application growth and needs.
12 |
13 | The default components use Tailwind CSS, a utility-first CSS framework.
14 | See the [Tailwind CSS documentation](https://tailwindcss.com) to learn
15 | how to customize them or feel free to swap in another framework altogether.
16 |
17 | Icons are provided by [heroicons](https://heroicons.com). See `icon/1` for usage.
18 | """
19 | use Phoenix.Component
20 |
21 | alias Phoenix.LiveView.JS
22 |
23 | @doc """
24 | Renders a modal.
25 |
26 | ## Examples
27 |
28 | <.modal id="confirm-modal">
29 | This is a modal.
30 |
31 |
32 | JS commands may be passed to the `:on_cancel` to configure
33 | the closing/cancel event, for example:
34 |
35 | <.modal id="confirm" on_cancel={JS.navigate(~p"/posts")}>
36 | This is another modal.
37 |
38 |
39 | """
40 | attr :id, :string, required: true
41 | attr :show, :boolean, default: false
42 | attr :on_cancel, JS, default: %JS{}
43 | slot :inner_block, required: true
44 |
45 | def modal(assigns) do
46 | ~H"""
47 |