-
Notifications
You must be signed in to change notification settings - Fork 44
feat(llc): speech recognition while muted #999
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
77ac97a
wip speech recognition
renefloor 6f7a69a
Refactor feature out of callState
renefloor 03162ce
Add documentation and test
renefloor 028bf9b
Add changelog
renefloor 6006f5d
formatting
renefloor f65a932
Apply suggestions from code review
renefloor 3afd2b3
Improve error handling
renefloor b260558
Merge remote-tracking branch 'origin/main' into feature/speech-recogn…
renefloor 4ba9730
Merge remote-tracking branch 'origin/main' into feature/speech-recogn…
renefloor 8f020b4
Merge branch 'main' into feature/speech-recognition-while-muted
renefloor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
packages/stream_video/lib/src/audio_processing/audio_recognition.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import 'dart:async'; | ||
|
||
abstract interface class AudioRecognition { | ||
Future<void> start({ | ||
required SoundStateChangedCallback onSoundStateChanged, | ||
}); | ||
|
||
Future<void> stop(); | ||
|
||
Future<void> dispose(); | ||
} | ||
|
||
typedef SoundStateChangedCallback = void Function(SoundState state); | ||
|
||
class SoundState { | ||
const SoundState({ | ||
required this.isSpeaking, | ||
required this.audioLevel, | ||
}); | ||
|
||
final bool isSpeaking; | ||
final double audioLevel; | ||
} | ||
180 changes: 180 additions & 0 deletions
180
packages/stream_video/lib/src/audio_processing/audio_recognition_webrtc.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
import 'dart:async'; | ||
import 'dart:math' as math; | ||
|
||
import 'package:collection/collection.dart'; | ||
import 'package:flutter/foundation.dart'; | ||
import 'package:stream_webrtc_flutter/stream_webrtc_flutter.dart' as rtc; | ||
import 'package:stream_webrtc_flutter/stream_webrtc_flutter.dart'; | ||
|
||
import '../../stream_video.dart'; | ||
import '../webrtc/model/stats/rtc_audio_source.dart'; | ||
import '../webrtc/model/stats/rtc_stats_mapper.dart'; | ||
|
||
class AudioRecognitionWebRTC implements AudioRecognition { | ||
AudioRecognitionWebRTC({this.config = const AudioRecognitionConfig()}) { | ||
_init(); | ||
} | ||
|
||
Completer<void>? _initCompleter; | ||
AudioRecognitionConfig config; | ||
|
||
late RTCPeerConnection _pc1; | ||
late RTCPeerConnection _pc2; | ||
MediaStream? _audioStream; | ||
|
||
VoidCallback? _disposeTimers; | ||
|
||
@override | ||
Future<void> start({ | ||
required SoundStateChangedCallback onSoundStateChanged, | ||
}) async { | ||
if (_initCompleter case final completer?) await completer.future; | ||
|
||
_disposeTimers = _startListening(onSoundStateChanged); | ||
} | ||
|
||
@override | ||
Future<void> stop() async { | ||
_disposeTimers?.call(); | ||
_disposeTimers = null; | ||
} | ||
|
||
@override | ||
Future<void> dispose() async { | ||
await stop(); | ||
await Future.wait([_pc1.close(), _pc2.close()]); | ||
await _cleanupAudioStream(); | ||
} | ||
|
||
Future<void> _init() async { | ||
_initCompleter = Completer<void>(); | ||
try { | ||
_pc1 = await rtc.createPeerConnection(const RTCConfiguration().toMap()); | ||
_pc2 = await rtc.createPeerConnection(const RTCConfiguration().toMap()); | ||
|
||
final audioStream = await rtc.navigator.mediaDevices.getUserMedia( | ||
const AudioConstraints().toMap(), | ||
); | ||
_audioStream = audioStream; | ||
|
||
_pc1.onIceCandidate = _pc2.addCandidate; | ||
_pc2.onIceCandidate = _pc1.addCandidate; | ||
|
||
audioStream.getAudioTracks().forEach((track) { | ||
_pc1.addTrack(track, audioStream); | ||
}); | ||
|
||
final offer = await _pc1.createOffer(); | ||
await _pc2.setRemoteDescription(offer); | ||
await _pc1.setLocalDescription(offer); | ||
|
||
final answer = await _pc2.createAnswer(); | ||
await _pc1.setRemoteDescription(answer); | ||
await _pc2.setLocalDescription(answer); | ||
_initCompleter?.complete(); | ||
_initCompleter = null; | ||
} catch (e, trace) { | ||
_initCompleter?.completeError(e, trace); | ||
} | ||
} | ||
|
||
VoidCallback _startListening(SoundStateChangedCallback onSoundStateChanged) { | ||
var baselineNoiseLevel = config.initialBaselineNoiseLevel; | ||
var speechDetected = false; | ||
Timer? speechTimer; | ||
Timer? silenceTimer; | ||
final audioLevelHistory = | ||
<double>[]; // Store recent audio levels for smoother detection | ||
|
||
Future<void> checkAudioLevel(Timer timer) async { | ||
final stats = await _pc1.getStats(); | ||
final audioMediaSourceStats = stats | ||
.map((stat) => stat.toRtcStats()) | ||
.whereType<RtcAudioSource>() | ||
.firstOrNull; | ||
|
||
final audioLevel = audioMediaSourceStats?.audioLevel; | ||
if (audioLevel == null) return; | ||
|
||
// Update audio level history (with max historyLength sized list) | ||
audioLevelHistory.add(audioLevel); | ||
if (audioLevelHistory.length > config.historyLength) { | ||
audioLevelHistory.removeAt(0); | ||
} | ||
|
||
if (audioLevelHistory.length < 5) return; | ||
|
||
// Calculate average audio level | ||
final averageAudioLevel = | ||
audioLevelHistory.reduce((a, b) => a + b) / audioLevelHistory.length; | ||
|
||
// Update baseline (if necessary) based on silence detection | ||
if (averageAudioLevel < baselineNoiseLevel * config.silenceThreshold) { | ||
silenceTimer ??= Timer(config.silenceTimeout, () { | ||
baselineNoiseLevel = math.min( | ||
averageAudioLevel * config.resetThreshold, | ||
baselineNoiseLevel, | ||
); | ||
}); | ||
} else { | ||
silenceTimer?.cancel(); | ||
silenceTimer = null; | ||
} | ||
|
||
// Check for speech detection | ||
if (averageAudioLevel > baselineNoiseLevel * config.speechThreshold) { | ||
if (!speechDetected) { | ||
speechDetected = true; | ||
onSoundStateChanged( | ||
SoundState(isSpeaking: true, audioLevel: averageAudioLevel)); | ||
} | ||
|
||
speechTimer?.cancel(); | ||
speechTimer = Timer(config.speechTimeout, () { | ||
speechDetected = false; | ||
onSoundStateChanged( | ||
SoundState(isSpeaking: false, audioLevel: averageAudioLevel), | ||
); | ||
speechTimer = null; | ||
}); | ||
} | ||
} | ||
|
||
final interval = | ||
Timer.periodic(const Duration(milliseconds: 100), checkAudioLevel); | ||
|
||
return () { | ||
speechTimer?.cancel(); | ||
silenceTimer?.cancel(); | ||
interval.cancel(); | ||
}; | ||
} | ||
|
||
Future<void> _cleanupAudioStream() async { | ||
_audioStream?.getAudioTracks().forEach((track) { | ||
track.stop(); | ||
}); | ||
await _audioStream?.dispose(); | ||
_audioStream = null; | ||
} | ||
} | ||
|
||
class AudioRecognitionConfig { | ||
const AudioRecognitionConfig({ | ||
this.initialBaselineNoiseLevel = 0.13, | ||
this.historyLength = 10, | ||
this.silenceThreshold = 1.1, | ||
this.speechThreshold = 5, | ||
this.resetThreshold = 0.9, | ||
this.speechTimeout = const Duration(milliseconds: 500), | ||
this.silenceTimeout = const Duration(seconds: 5), | ||
}); | ||
|
||
final double initialBaselineNoiseLevel; | ||
final int historyLength; | ||
final double silenceThreshold; | ||
final double speechThreshold; | ||
final double resetThreshold; | ||
final Duration speechTimeout; | ||
final Duration silenceTimeout; | ||
} | ||
renefloor marked this conversation as resolved.
Show resolved
Hide resolved
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.