| 1 | /* |
| 2 | * Copyright 2025 LiveKit, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #pragma once |
| 18 | |
| 19 | #include <memory> |
| 20 | |
| 21 | #include "api/audio/audio_mixer.h" |
| 22 | #include "api/scoped_refptr.h" |
| 23 | #include "modules/audio_mixer/audio_mixer_impl.h" |
| 24 | #include "modules/audio_processing/audio_buffer.h" |
| 25 | #include "rtc_base/synchronization/mutex.h" |
| 26 | #include "rust/cxx.h" |
| 27 | |
| 28 | namespace livekit_ffi { |
| 29 | class AudioMixer; |
| 30 | class NativeAudioFrame; |
| 31 | } // namespace livekit_ffi |
| 32 | |
| 33 | #include "webrtc-sys/src/audio_mixer.rs.h" |
| 34 | |
| 35 | namespace livekit_ffi { |
| 36 | |
| 37 | class NativeAudioFrame { |
| 38 | public: |
| 39 | NativeAudioFrame(webrtc::AudioFrame* frame) : frame_(frame) {} |
| 40 | void update_frame(uint32_t timestamp, |
| 41 | const int16_t* data, |
| 42 | size_t samples_per_channel, |
| 43 | int sample_rate_hz, |
| 44 | size_t num_channels); |
| 45 | |
| 46 | private: |
| 47 | webrtc::AudioFrame* frame_; |
| 48 | }; |
| 49 | |
| 50 | class AudioMixerSource : public webrtc::AudioMixer::Source { |
| 51 | public: |
| 52 | AudioMixerSource(rust::Box<AudioMixerSourceWrapper> source); |
| 53 | |
| 54 | AudioFrameInfo GetAudioFrameWithInfo( |
| 55 | int sample_rate_hz, |
| 56 | webrtc::AudioFrame* audio_frame) override; |
| 57 | |
| 58 | int Ssrc() const override; |
| 59 | |
| 60 | int PreferredSampleRate() const override; |
| 61 | |
| 62 | ~AudioMixerSource() {} |
| 63 | |
| 64 | private: |
| 65 | rust::Box<AudioMixerSourceWrapper> source_; |
| 66 | }; |
| 67 | |
| 68 | class AudioMixer { |
| 69 | public: |
| 70 | AudioMixer(); |
| 71 | |
| 72 | void add_source(rust::Box<AudioMixerSourceWrapper> source); |
| 73 | |
| 74 | void remove_source(int ssrc); |
| 75 | |
| 76 | size_t mix(size_t num_channels); |
| 77 | const int16_t* data() const; |
| 78 | |
| 79 | private: |
| 80 | mutable webrtc::Mutex sources_mutex_; |
| 81 | webrtc::AudioFrame frame_; |
| 82 | std::vector<std::shared_ptr<AudioMixerSource>> sources_; |
| 83 | webrtc::scoped_refptr<webrtc::AudioMixer> audio_mixer_; |
| 84 | }; |
| 85 | |
| 86 | std::unique_ptr<AudioMixer> create_audio_mixer(); |
| 87 | |
| 88 | } // namespace livekit_ffi |