| 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 | #include <mutex> |
| 21 | |
| 22 | #include "api/data_channel_interface.h" |
| 23 | #include "livekit/webrtc.h" |
| 24 | #include "rtc_base/synchronization/mutex.h" |
| 25 | #include "rust/cxx.h" |
| 26 | |
| 27 | namespace livekit_ffi { |
| 28 | class DataChannel; |
| 29 | } // namespace livekit_ffi |
| 30 | #include "webrtc-sys/src/data_channel.rs.h" |
| 31 | |
| 32 | namespace livekit_ffi { |
| 33 | |
| 34 | class NativeDataChannelObserver; |
| 35 | |
| 36 | webrtc::DataChannelInit to_native_data_channel_init(DataChannelInit init); |
| 37 | |
| 38 | class DataChannel { |
| 39 | public: |
| 40 | explicit DataChannel( |
| 41 | std::shared_ptr<RtcRuntime> rtc_runtime, |
| 42 | webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel); |
| 43 | ~DataChannel(); |
| 44 | |
| 45 | void register_observer(rust::Box<DataChannelObserverWrapper> observer) const; |
| 46 | void unregister_observer() const; |
| 47 | bool send(const DataBuffer& buffer) const; |
| 48 | int id() const; |
| 49 | rust::String label() const; |
| 50 | DataState state() const; |
| 51 | void close() const; |
| 52 | uint64_t buffered_amount() const; |
| 53 | |
| 54 | private: |
| 55 | mutable webrtc::Mutex mutex_; |
| 56 | std::shared_ptr<RtcRuntime> rtc_runtime_; |
| 57 | webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel_; |
| 58 | mutable std::unique_ptr<NativeDataChannelObserver> observer_; |
| 59 | }; |
| 60 | |
| 61 | static std::shared_ptr<DataChannel> _shared_data_channel() { |
| 62 | return nullptr; // Ignore |
| 63 | } |
| 64 | |
| 65 | class NativeDataChannelObserver : public webrtc::DataChannelObserver { |
| 66 | public: |
| 67 | NativeDataChannelObserver(rust::Box<DataChannelObserverWrapper> observer, |
| 68 | const DataChannel* dc); |
| 69 | |
| 70 | void OnStateChange() override; |
| 71 | void OnMessage(const webrtc::DataBuffer& buffer) override; |
| 72 | void OnBufferedAmountChange(uint64_t sent_data_size) override; |
| 73 | |
| 74 | private: |
| 75 | rust::Box<DataChannelObserverWrapper> observer_; |
| 76 | const DataChannel* dc_; |
| 77 | }; |
| 78 | |
| 79 | } // namespace livekit_ffi |