enableVideo method
Enables the local cam and starts producing the stream with the label video
Implementation
Future<MediaStream?> enableVideo({MediaStream? customVideoStream}) async {
logger.i('enableVideo called');
try {
if (!checkPermission(produceSourcesCheck: ProduceSources.cam)) {
logger.e('❌ Cannot Enable Video, Permission Denied');
throw Exception('❌ Cannot Enable Video, Permission Denied');
}
final existingStream = _activeStreams['video'];
if (existingStream != null) {
logger.w('🔔 Cam Stream Already Enabled');
return null;
}
// transport are being created here
if (_sendTransport == null) {
await _createTransportOnServer(transportType: TransportType.send);
}
MediaStream? stream;
if (customVideoStream != null) {
stream = customVideoStream;
} else {
final ongoingStreamFuture = _pendingFetchingStream['cam'];
if (ongoingStreamFuture != null) {
await ongoingStreamFuture;
} else {
final streamFuture =
deviceHandler.fetchStream(mediaDevice: CustomMediaDevice.cam);
_pendingFetchingStream['cam'] = streamFuture;
}
final pendingFuture = _pendingFetchingStream['cam'];
if (pendingFuture == null) {
logger.i('🔔 Pending Cam Future Not Found');
return null;
}
final fetchedStream = await pendingFuture;
if (fetchedStream == null) {
logger.e('❌ Stream Not Found, cannot do enableVideo');
throw Exception('❌ Stream Not Found');
}
stream = fetchedStream;
}
if (deviceHandler.videoRenderer == null) {
deviceHandler.videoRenderer = RTCVideoRenderer();
await deviceHandler.videoRenderer?.initialize();
}
deviceHandler.videoRenderer?.srcObject = stream;
if (stream != null) {
_activeStreams['video'] = stream;
emit('stream-fetched', {
'mediaKind': 'cam',
'stream': stream,
'label': 'video',
});
}
logger.i(
"enableVideo | fetched stream => ${stream?.getVideoTracks().first}",
);
await produce(
label: 'video',
stream: stream,
appData: {
'producerPeerId': peerId,
},
stopTrackOnClose: true,
);
_pendingFetchingStream.remove('cam');
return stream;
} catch (error) {
deviceHandler.stopStream(_activeStreams['video']);
_activeStreams.remove('video');
_pendingFetchingStream.remove('cam');
logger.e('❌ Error Enabling Video | error: $error');
rethrow;
}
}