forked from apiko-dev/amazon-ivs-react-native-broadcast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
337 lines (311 loc) · 8.51 KB
/
App.tsx
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import React, { FC, useEffect, useState, useRef, useCallback } from 'react';
import {
Text,
Modal,
View,
Alert,
AppState,
StyleSheet,
ActivityIndicator,
TouchableOpacity,
TouchableOpacityProps,
} from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import { rtmpsUrl, streamKey } from '../app.json';
import {
IAudioStats,
StateStatusUnion,
IBroadcastSessionError,
IVSBroadcastCameraView,
IIVSBroadcastCameraView,
} from 'amazon-ivs-react-native-broadcast';
enum SessionReadyStatus {
None = 'NONE',
Ready = 'READY',
NotReady = 'NOT_READY',
}
const { None, NotReady, Ready } = SessionReadyStatus;
const INITIAL_BROADCAST_STATE_STATUS = 'INVALID' as const;
const INITIAL_STATE = {
readyStatus: None,
stateStatus: INITIAL_BROADCAST_STATE_STATUS,
};
const INITIAL_META_DATA_STATE = {
audioStats: {
rms: 0,
peak: 0,
},
streamQuality: 0,
networkHealth: 0,
};
const VIDEO_CONFIG = {
width: 1920,
height: 1080,
bitrate: 7500000,
targetFrameRate: 60,
keyframeInterval: 2,
isBFrames: true,
isAutoBitrate: true,
maxBitrate: 8500000,
minBitrate: 1500000,
} as const;
const AUDIO_CONFIG = {
bitrate: 128000,
} as const;
const Spinner = () => <ActivityIndicator size="large" style={s.spinner} />;
const Button: FC<{
title: string;
onPress: Exclude<TouchableOpacityProps['onPress'], undefined>;
}> = ({ onPress, title }) => (
<TouchableOpacity style={s.button} onPress={onPress}>
<Text style={s.buttonText}>{title}</Text>
</TouchableOpacity>
);
const App: FC = () => {
const cameraViewRef = useRef<IIVSBroadcastCameraView>(null);
const [{ stateStatus, readyStatus }, setState] = useState<{
readonly stateStatus: StateStatusUnion;
readonly readyStatus: SessionReadyStatus;
}>(INITIAL_STATE);
const [{ audioStats, networkHealth, streamQuality }, setMetaData] = useState<{
readonly streamQuality: number;
readonly networkHealth: number;
readonly audioStats: {
readonly rms: number;
readonly peak: number;
};
}>(INITIAL_META_DATA_STATE);
const isConnecting = stateStatus === 'CONNECTING';
const isConnected = stateStatus === 'CONNECTED';
const isDisconnected = stateStatus === 'DISCONNECTED';
useEffect(() => {
const subscription = AppState.addEventListener('change', nextAppState => {
if (nextAppState === 'background') {
cameraViewRef.current?.stop();
}
});
return () => {
subscription.remove();
};
}, []);
useEffect(() => {
if (readyStatus === NotReady) {
Alert.alert(
'Sorry, something went wrong :(',
'Broadcast session is not ready. Please try again.'
);
}
}, [readyStatus]);
const onIsBroadcastReadyHandler = useCallback(
(isReady: boolean) =>
setState(currentState => ({
...currentState,
readyStatus: isReady ? Ready : NotReady,
})),
[]
);
const onBroadcastStateChangedHandler = useCallback(
(status: StateStatusUnion) =>
setState(currentState => ({
...currentState,
stateStatus: status,
})),
[]
);
const onBroadcastAudioStatsHandler = useCallback(
(stats: IAudioStats) =>
setMetaData(currentState => ({
...currentState,
audioStats: {
...currentState.audioStats,
...stats,
},
})),
[]
);
const onBroadcastQualityChangedHandler = useCallback(
(quality: number) =>
setMetaData(currentState => ({
...currentState,
streamQuality: quality,
})),
[]
);
const onNetworkHealthChangedHandler = useCallback(
(health: number) =>
setMetaData(currentState => ({
...currentState,
networkHealth: health,
})),
[]
);
const onBroadcastErrorHandler = useCallback(
(exception: IBroadcastSessionError) =>
console.log('Broadcast session error: ', exception),
[]
);
const onErrorHandler = useCallback(
(errorMessage: string) =>
console.log('Internal module error: ', errorMessage),
[]
);
const onMediaServicesWereLostHandler = useCallback(
() => console.log('The media server is terminated.'),
[]
);
const onMediaServicesWereResetHandler = useCallback(
() => console.log('The media server is restarted.'),
[]
);
const onPressPlayButtonHandler = useCallback(
() => cameraViewRef.current?.start(),
[]
);
const onPressStopButtonHandler = useCallback(
() => cameraViewRef.current?.stop(),
[]
);
const onPressSwapCameraButtonHandler = useCallback(
() => cameraViewRef.current?.swapCamera(),
[]
);
const isStartButtonVisible =
isDisconnected || stateStatus === INITIAL_BROADCAST_STATE_STATUS;
return (
<>
<IVSBroadcastCameraView
ref={cameraViewRef}
style={s.cameraView}
rtmpsUrl={rtmpsUrl}
streamKey={streamKey}
videoConfig={VIDEO_CONFIG}
audioConfig={AUDIO_CONFIG}
onError={onErrorHandler}
onBroadcastError={onBroadcastErrorHandler}
onIsBroadcastReady={onIsBroadcastReadyHandler}
onBroadcastAudioStats={onBroadcastAudioStatsHandler}
onNetworkHealthChanged={onNetworkHealthChangedHandler}
onBroadcastStateChanged={onBroadcastStateChangedHandler}
onBroadcastQualityChanged={onBroadcastQualityChangedHandler}
onMediaServicesWereLost={onMediaServicesWereLostHandler}
onMediaServicesWereReset={onMediaServicesWereResetHandler}
{...(__DEV__ && {
logLevel: 'debug',
sessionLogLevel: 'debug',
})}
/>
<Modal
visible
transparent
animationType="fade"
supportedOrientations={['landscape', 'portrait']}
>
<SafeAreaProvider>
{readyStatus === None ? (
<Spinner />
) : (
readyStatus === Ready && (
<SafeAreaView style={s.primaryContainer}>
<View style={s.topContainer}>
<View style={s.topButtonContainer}>
<Button
title="Swap"
onPress={onPressSwapCameraButtonHandler}
/>
{isConnected && (
<Button title="Stop" onPress={onPressStopButtonHandler} />
)}
</View>
</View>
{(isStartButtonVisible || isConnecting) && (
<View style={s.middleContainer}>
{isStartButtonVisible && (
<Button
title="Start"
onPress={onPressPlayButtonHandler}
/>
)}
{isConnecting && <Spinner />}
</View>
)}
<View style={s.bottomContainer}>
<View style={s.metaDataContainer}>
<Text
style={s.metaDataText}
>{`Peak ${audioStats.peak?.toFixed(
2
)}, Rms: ${audioStats.rms?.toFixed(2)}`}</Text>
<Text
style={s.metaDataText}
>{`Stream quality: ${streamQuality}`}</Text>
<Text
style={s.metaDataText}
>{`Network health: ${networkHealth}`}</Text>
</View>
{isConnected && <Text style={s.liveText}>LIVE</Text>}
</View>
</SafeAreaView>
)
)}
</SafeAreaProvider>
</Modal>
</>
);
};
const s = StyleSheet.create({
spinner: {
flex: 1,
},
topContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
},
topButtonContainer: {
flexDirection: 'row',
},
middleContainer: {
flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'center',
},
bottomContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'flex-end',
},
button: {
marginHorizontal: 8,
},
buttonText: {
padding: 8,
borderRadius: 8,
fontSize: 20,
color: '#ffffff',
backgroundColor: 'rgba(128, 128, 128, 0.4)',
},
metaDataContainer: {
flex: 1,
},
metaDataText: {
color: '#ffffff',
},
liveText: {
color: '#ffffff',
padding: 8,
backgroundColor: '#FF5C5C',
borderRadius: 8,
},
cameraView: {
flex: 1,
backgroundColor: '#000000',
},
primaryContainer: {
flex: 1,
padding: 16,
justifyContent: 'space-between',
},
});
export default App;