xonecas.io
4828
Sr

stream-together / commit bb4f3cf

Several improvements and refactoring

Broke down AgoraHost into smaller chunks using Hooks.
Refactored several components to use the appropriate hooks instead of
passing down props.

sean2024-06-28 bb4f3cfcb4067951389569ee790d452fd5411654 parent 4dda7b2

9 files changed

app/[slug]/page.tsx+1−1
@@ -10,7 +10,7 @@ const AgoraGuest = dynamic(() => import("@/components/agora-guest"), {
1010 ssr: false,
1111 });
1212
13-export default function StreamSetupPage() {
13+export default function ViewerPage() {
1414 return (
1515 <AgoraProvider>
1616 <div className="flex flex-col items-center gap-16">
app/[slug]/stream/page.tsx+2−3
@@ -12,12 +12,11 @@ import { HOST, OWNER } from "@/lib/config";
1212 const AgoraProvider = dynamic(() => import("@/components/agora-provider"), {
1313 ssr: false,
1414 });
15-
1615 const AgoraHost = dynamic(() => import("@/components/agora-host"), {
1716 ssr: false,
1817 });
1918
20-export default function StreamSetupPage() {
19+export default function HostPage() {
2120 const [currentUrl, setCurrentUrl] = useState("");
2221 const [copied, copy] = useCopyToClipboard();
2322 const searchParams = useSearchParams();
@@ -34,7 +33,7 @@ export default function StreamSetupPage() {
3433 <AgoraProvider>
3534 <div className="flex flex-col items-center gap-16">
3635 {userType === OWNER && (
37- <div className="max-w-xl w-full text-center">
36+ <div className="text-center p-8 bg-stone-800 shadow-md shadow-stone-800 rounded-2xl max-w-xl">
3837 <p className="text-lg p-2">
3938 Share this url with your co-host for them to join you!
4039 </p>
app/page.tsx+1−2
@@ -17,7 +17,6 @@ export default function Home() {
1717 const handleChange = useCallback(
1818 (e: React.ChangeEvent<HTMLInputElement>) => {
1919 setTitle(e.target.value);
20- // Clear the error if it exists after a new change
2120 if (error) setError("");
2221 },
2322 [error, setTitle],
@@ -27,7 +26,7 @@ export default function Home() {
2726 if (!title) setError("Please tell us the title of your stream first.");
2827 else {
2928 const slug = slugify(title);
30- router.push("/" + slug + "/host");
29+ router.push("/" + slug + "/stream");
3130 }
3231 }, [title, router]);
3332
components/agora-host.tsx+33−83
@@ -1,20 +1,19 @@
11 "use client";
22
3-import AgoraRTC, {
3+import {
44 LocalUser,
55 RemoteUser,
66 useIsConnected,
77 useJoin,
8- useLocalCameraTrack,
9- useLocalMicrophoneTrack,
108 usePublish,
119 useRemoteUsers,
1210 } from "agora-rtc-react";
13-import { useCallback, useEffect, useState } from "react";
11+import { useCallback, useState } from "react";
1412 import { ImSpinner10 } from "react-icons/im";
13+import { IoEye } from "react-icons/io5";
1514
16-import useNoiseReduction from "@/hooks/agora-ai-noise-reduction";
17-import useVirtualBackground from "@/hooks/agora-virtual-background";
15+import useCamera from "@/hooks/use-camera";
16+import useMicrophone from "@/hooks/use-microphone";
1817 import { appId, channel, HOST, OWNER, token } from "@/lib/config";
1918
2019 import EndStreamButton from "./end-stream-button";
@@ -30,69 +29,15 @@ export default function AgoraHost({
3029 userType,
3130 }: Readonly<{ userType: number }>) {
3231 const [showSettingsModal, setShowSettingsModal] = useState(false);
33-
3432 const [callStarted, setCallStarted] = useState(false);
3533 const [videoStarted, setVideoStarted] = useState(false);
3634 const [audioStarted, setAudioStarted] = useState(false);
37-
38- const [availableCameras, setAvailableCameras] = useState<
39- { id: string; label: string }[]
40- >([]);
41- const [selectedCameraId, setSelectedCameraId] = useState("");
42-
43- useEffect(() => {
44- const getCameras = async () => {
45- const cameras = await AgoraRTC.getCameras();
46- setAvailableCameras(
47- cameras.map((c) => ({ id: c.deviceId, label: c.label })),
48- );
49- // Choose the first one as a default
50- setSelectedCameraId(cameras[0].deviceId);
51- };
52- getCameras();
53- }, []);
54-
55- const { localCameraTrack } = useLocalCameraTrack(videoStarted, {
56- cameraId: selectedCameraId,
57- });
58-
59- const { localMicrophoneTrack } = useLocalMicrophoneTrack(audioStarted);
60- useNoiseReduction({ localMicrophoneTrack });
61-
35+ const { localCameraTrack } = useCamera(videoStarted);
36+ const { localMicrophoneTrack } = useMicrophone(audioStarted);
6237 const isConnected = useIsConnected();
63-
64- const handleStarCall = useCallback(() => {
65- setCallStarted(true);
66- }, []);
67-
68- const handleEndCall = useCallback(() => {
69- setCallStarted(false);
70- }, []);
71-
72- const handleToggleAudio = useCallback(() => {
73- setAudioStarted(!audioStarted);
74- }, [audioStarted]);
75-
76- const handleToggleVideo = useCallback(() => {
77- setVideoStarted(!videoStarted);
78- }, [videoStarted]);
79-
80- const virtualBackgroundRef = useVirtualBackground({ localCameraTrack });
81-
82- const handleBlurBackground = useCallback(() => {
83- const enableBlur = async () => {
84- if (virtualBackgroundRef.current?.enabled) {
85- virtualBackgroundRef.current?.disable();
86- } else {
87- virtualBackgroundRef.current?.setOptions({
88- type: "blur",
89- blurDegree: 2,
90- });
91- virtualBackgroundRef.current?.enable();
92- }
93- };
94- void enableBlur();
95- }, [virtualBackgroundRef]);
38+ const remoteUsers = useRemoteUsers();
39+ const otherHosts = remoteUsers.filter((u) => u.uid === HOST);
40+ const guests = remoteUsers.filter((u) => u.uid !== HOST && u.uid !== OWNER);
9641
9742 useJoin(
9843 {
@@ -106,12 +51,16 @@ export default function AgoraHost({
10651
10752 usePublish([localMicrophoneTrack, localCameraTrack]);
10853
109- const remoteUsers = useRemoteUsers();
110- const otherHosts = remoteUsers.filter((u) => u.uid === HOST);
111- const guests = remoteUsers.filter((u) => u.uid !== HOST && u.uid !== OWNER);
54+ const handleToggleAudio = useCallback(() => {
55+ setAudioStarted(!audioStarted);
56+ }, [audioStarted]);
57+
58+ const handleToggleVideo = useCallback(() => {
59+ setVideoStarted(!videoStarted);
60+ }, [videoStarted]);
11261
11362 return (
114- <div className="w-full">
63+ <div className="w-full flex flex-col justify-center items-center gap-4">
11564 <div className="flex flex-col md:flex-row gap-8 w-full justify-center items-center">
11665 <div className="w-full flex flex-col gap-2 max-w-2xl">
11766 <div className="rounded-3xl overflow-hidden bg-black w-full aspect-[4/3]">
@@ -122,10 +71,8 @@ export default function AgoraHost({
12271 micOn={audioStarted}
12372 playAudio={false}
12473 >
125- <div className="flex flex-col justify-between h-full p-2">
126- <div className="flex flex-row justify-between">
127- <p className="p-2">Your broadcast</p>
128-
74+ <div className="flex flex-col justify-between h-full p-4">
75+ <div className="flex flex-row justify-end">
12976 <Modal
13077 openButton={
13178 <SettingsButton
@@ -137,10 +84,8 @@ export default function AgoraHost({
13784 >
13885 <div className="p-4 bg-stone-800 rounded-2xl flex flex-col gap-4 text-left">
13986 <StreamSettings
140- availableCameras={availableCameras}
141- selectedCameraId={selectedCameraId}
142- setSelectedCameraId={setSelectedCameraId}
143- handleBlurBackground={handleBlurBackground}
87+ audioStarted={audioStarted}
88+ videoStarted={videoStarted}
14489 />
14590
14691 <div className="text-center">
@@ -164,7 +109,9 @@ export default function AgoraHost({
164109 videoStarted={videoStarted}
165110 handleToggleVideo={handleToggleVideo}
166111 />
167- <EndStreamButton handleEndCall={handleEndCall} />
112+ <EndStreamButton
113+ handleEndCall={() => setCallStarted(false)}
114+ />
168115 </div>
169116 ) : callStarted ? (
170117 <div className="flex flex-col flex-grow items-center justify-center">
@@ -172,7 +119,9 @@ export default function AgoraHost({
172119 </div>
173120 ) : (
174121 <div className="flex flex-row flex-grow justify-center">
175- <StartStreamButton handleStartCall={handleStarCall} />
122+ <StartStreamButton
123+ handleStartCall={() => setCallStarted(true)}
124+ />
176125 </div>
177126 )}
178127 </div>
@@ -186,15 +135,16 @@ export default function AgoraHost({
186135 key={host.uid}
187136 className="rounded-3xl overflow-hidden bg-black w-full max-w-2xl aspect-[4/3]"
188137 >
189- <RemoteUser user={host}>
190- <p className="p-4">{host.uid}</p>
191- </RemoteUser>
138+ <RemoteUser user={host} />
192139 </div>
193140 );
194141 })}
195142 </div>
196143
197- <div className="text-center">People watching: {guests?.length ?? 0}</div>
144+ <div className="text-center p-8 bg-stone-800 shadow-md shadow-stone-800 rounded-2xl max-w-2xl flex flex-row justify-center gap-2">
145+ <IoEye size="1.5em" />
146+ <p>Viewers: {guests?.length ?? 0}</p>
147+ </div>
198148 </div>
199149 );
200150 }
components/agora-provider.tsx+0−2
@@ -11,11 +11,9 @@ export default function AgoraProvider({
1111 }>) {
1212 const [client, setClient] = useState<IAgoraRTCClient | null>(null);
1313
14- // Because of server side rendering, we need to initialize agoraIO only on the client
1514 useEffect(() => {
1615 const initializeAgoraSDK = async () => {
1716 const AgoraRTC = (await import("agora-rtc-react")).default;
18- // TODO: I think I really need `mode: "live"` in the config
1917 const agoraClient = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
2018
2119 setClient(agoraClient);
components/app-layout.tsx+6−2
@@ -1,3 +1,5 @@
1+import { FaHeart } from "react-icons/fa6";
2+
13 import Header from "./header";
24
35 export default function AppLayout({
@@ -9,9 +11,11 @@ export default function AppLayout({
911 <div className="flex flex-col justify-start h-screen gap-16 p-4">
1012 <Header />
1113 <div className="flex-grow">{children}</div>
12- <p className="text-sm italic flex flex-row items-center justify-center justify-self-end">
14+ <p className="text-sm italic flex flex-row items-center justify-center justify-self-end gap-2">
1315 <span>Made with care by Sean</span>
14- <span className="text-6xl pb-2 text-rose-400">&#x1F394;</span>
16+ <span className="text-rose-400">
17+ <FaHeart size="1.25em" />
18+ </span>
1519 </p>
1620 </div>
1721 );
components/stream-settings.tsx+72−21
@@ -1,24 +1,52 @@
1-import PrimaryButton from "./primary-button";
2-import SecondaryButton from "./secondary-button";
1+import { useCallback, useState } from "react";
2+
3+import useVirtualBackground from "@/hooks/agora-virtual-background";
4+import useCamera from "@/hooks/use-camera";
5+import useMicrophone from "@/hooks/use-microphone";
36
47 export default function StreamSettings({
5- availableCameras,
6- selectedCameraId,
7- setSelectedCameraId,
8- // availableMicrophones,
9- // selectedMicrophoneId,
10- // setSelectedMicrophone,
11- handleBlurBackground,
8+ audioStarted,
9+ videoStarted,
1210 }: Readonly<{
13- availableCameras: { id: string; label: string }[];
14- selectedCameraId: string;
15- setSelectedCameraId: (agr0: string) => void;
16- handleBlurBackground: () => void;
11+ audioStarted: boolean;
12+ videoStarted: boolean;
1713 }>) {
14+ const {
15+ localCameraTrack,
16+ availableCameras,
17+ selectedCameraId,
18+ setSelectedCameraId,
19+ } = useCamera(videoStarted);
20+
21+ const {
22+ availableMicrophones,
23+ selectedMicrophoneId,
24+ setSelectedMicrophoneId,
25+ } = useMicrophone(audioStarted);
26+
27+ const virtualBackgroundRef = useVirtualBackground({ localCameraTrack });
28+ const [backgroundBlurred, setBackgroundBlurred] = useState(false);
29+
30+ const handleBlurBackground = useCallback(() => {
31+ const enableBlur = async () => {
32+ if (backgroundBlurred) {
33+ virtualBackgroundRef.current?.disable();
34+ } else {
35+ virtualBackgroundRef.current?.setOptions({
36+ type: "blur",
37+ blurDegree: 2,
38+ });
39+ virtualBackgroundRef.current?.enable();
40+ }
41+ };
42+ void enableBlur();
43+ }, [virtualBackgroundRef, backgroundBlurred]);
44+
1845 return (
1946 <>
2047 <div>
2148 <h4 className="font-bold pb-4">Select your video device:</h4>
49+
2250 {availableCameras.map((c) => {
2351 return (
2452 <label key={c.id} className="flex flex-row gap-2">
@@ -36,17 +64,40 @@ export default function StreamSettings({
3664 </label>
3765 );
3866 })}
67+
68+ <label className="flex flex-row gap-2 pt-2">
69+ <input
70+ type="checkbox"
71+ onChange={() => {
72+ void handleBlurBackground();
73+ setBackgroundBlurred(!backgroundBlurred);
74+ }}
75+ />
76+ <p>Blur your background?</p>
77+ </label>
3978 </div>
4079
80+ <div className="border-t-stone-700 border-t-2"></div>
81+
4182 <div>
42- <h4 className="font-bold pb-4">Blur your background?</h4>
43- <div className="flex flex-row justify-start">
44- <button onClick={handleBlurBackground}>
45- <SecondaryButton>
46- <p className="px-4 py-2">Toggle</p>
47- </SecondaryButton>
48- </button>
49- </div>
83+ <h4 className="font-bold pb-4">Select your audio device:</h4>
84+ {availableMicrophones.map((m) => {
85+ return (
86+ <label key={m.id} className="flex flex-row gap-2">
87+ <input
88+ type="radio"
89+ name="selected-microphone"
90+ value={m.id}
91+ checked={m.id === selectedMicrophoneId}
92+ onChange={(e) => {
93+ const id = e.target.value;
94+ setSelectedMicrophoneId(id);
95+ }}
96+ />
97+ <div>{m.label}</div>
98+ </label>
99+ );
100+ })}
50101 </div>
51102 </>
52103 );
hooks/use-camera.ts+31−0
@@ -0,0 +1,31 @@
1+import AgoraRTC, { useLocalCameraTrack } from "agora-rtc-react";
2+import { useEffect, useState } from "react";
3+
4+export default function useCamera(videoStarted: boolean) {
5+ const [availableCameras, setAvailableCameras] = useState<
6+ { id: string; label: string }[]
7+ >([]);
8+ const [selectedCameraId, setSelectedCameraId] = useState("");
9+
10+ useEffect(() => {
11+ const getCameras = async () => {
12+ const cameras = await AgoraRTC.getCameras();
13+ setAvailableCameras(
14+ cameras.map((c) => ({ id: c.deviceId, label: c.label })),
15+ );
16+ setSelectedCameraId(cameras[0].deviceId);
17+ };
18+ void getCameras();
19+ }, []);
20+
21+ const { localCameraTrack } = useLocalCameraTrack(videoStarted, {
22+ cameraId: selectedCameraId,
23+ });
24+
25+ return {
26+ localCameraTrack,
27+ availableCameras,
28+ selectedCameraId,
29+ setSelectedCameraId,
30+ };
31+}
hooks/use-microphone.ts+33−0
@@ -0,0 +1,33 @@
1+import AgoraRTC, { useLocalMicrophoneTrack } from "agora-rtc-react";
2+import { useEffect, useState } from "react";
3+
4+import useNoiseReduction from "./agora-ai-noise-reduction";
5+
6+export default function useMicrophone(audioStarted: boolean) {
7+ const [availableMicrophones, setAvailableMicrophones] = useState<
8+ { id: string; label: string }[]
9+ >([]);
10+
11+ const [selectedMicrophoneId, setSelectedMicrophoneId] = useState("");
12+
13+ useEffect(() => {
14+ const getCameras = async () => {
15+ const cameras = await AgoraRTC.getCameras();
16+ setAvailableMicrophones(
17+ cameras.map((c) => ({ id: c.deviceId, label: c.label })),
18+ );
19+ setSelectedMicrophoneId(cameras[0].deviceId);
20+ };
21+ void getCameras();
22+ }, []);
23+
24+ const { localMicrophoneTrack } = useLocalMicrophoneTrack(audioStarted);
25+ useNoiseReduction({ localMicrophoneTrack });
26+
27+ return {
28+ localMicrophoneTrack,
29+ availableMicrophones,
30+ selectedMicrophoneId,
31+ setSelectedMicrophoneId,
32+ };
33+}