| 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 | #include "livekit/webrtc.h" |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <atomic> |
| 21 | #include <iostream> |
| 22 | #include <memory> |
| 23 | |
| 24 | #include "livekit/audio_track.h" |
| 25 | #include "livekit/media_stream_track.h" |
| 26 | #include "livekit/rtp_receiver.h" |
| 27 | #include "livekit/rtp_sender.h" |
| 28 | #include "livekit/video_track.h" |
| 29 | #include "rtc_base/logging.h" |
| 30 | #include "rtc_base/crypto_random.h" |
| 31 | #include "rtc_base/synchronization/mutex.h" |
| 32 | |
| 33 | #ifdef WEBRTC_WIN |
| 34 | #ifndef NOMINMAX |
| 35 | #define NOMINMAX |
| 36 | #endif |
| 37 | #include <windows.h> |
| 38 | #include <dshow.h> |
| 39 | #include <ks.h> |
| 40 | #include <ksmedia.h> |
| 41 | #include <wrl/client.h> |
| 42 | |
| 43 | #include "rtc_base/win32.h" |
| 44 | #endif |
| 45 | |
| 46 | namespace livekit_ffi { |
| 47 | |
| 48 | static webrtc::Mutex g_mutex{}; |
| 49 | // Can't be atomic, we're using a Mutex because we need to wait for the |
| 50 | // execution of the first init |
| 51 | static uint32_t g_release_counter(0); |
| 52 | |
| 53 | RtcRuntime::RtcRuntime() { |
| 54 | RTC_LOG(LS_VERBOSE) << "RtcRuntime()"; |
| 55 | |
| 56 | { |
| 57 | // Not the best way to do it... |
| 58 | webrtc::MutexLock lock(&g_mutex); |
| 59 | if (g_release_counter == 0) { |
| 60 | RTC_CHECK(webrtc::InitializeSSL()) << "Failed to InitializeSSL()"; |
| 61 | |
| 62 | #ifdef WEBRTC_WIN |
| 63 | WSADATA data; |
| 64 | WSAStartup(MAKEWORD(1, 0), &data); |
| 65 | #endif |
| 66 | } |
| 67 | g_release_counter++; |
| 68 | } |
| 69 | |
| 70 | network_thread_ = webrtc::Thread::CreateWithSocketServer(); |
| 71 | network_thread_->SetName("network_thread", &network_thread_); |
| 72 | network_thread_->Start(); |
| 73 | worker_thread_ = webrtc::Thread::Create(); |
| 74 | worker_thread_->SetName("worker_thread", &worker_thread_); |
| 75 | worker_thread_->Start(); |
| 76 | signaling_thread_ = webrtc::Thread::Create(); |
| 77 | signaling_thread_->SetName("signaling_thread", &signaling_thread_); |
| 78 | signaling_thread_->Start(); |
| 79 | } |
| 80 | |
| 81 | RtcRuntime::~RtcRuntime() { |
| 82 | RTC_LOG(LS_VERBOSE) << "~RtcRuntime()"; |
| 83 | |
| 84 | worker_thread_->Stop(); |
| 85 | signaling_thread_->Stop(); |
| 86 | network_thread_->Stop(); |
| 87 | |
| 88 | { |
| 89 | webrtc::MutexLock lock(&g_mutex); |
| 90 | g_release_counter--; |
| 91 | if (g_release_counter == 0) { |
| 92 | RTC_CHECK(webrtc::CleanupSSL()) << "Failed to CleanupSSL()"; |
| 93 | |
| 94 | #ifdef WEBRTC_WIN |
| 95 | WSACleanup(); |
| 96 | #endif |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | webrtc::Thread* RtcRuntime::network_thread() const { |
| 102 | return network_thread_.get(); |
| 103 | } |
| 104 | |
| 105 | webrtc::Thread* RtcRuntime::worker_thread() const { |
| 106 | return worker_thread_.get(); |
| 107 | } |
| 108 | |
| 109 | webrtc::Thread* RtcRuntime::signaling_thread() const { |
| 110 | return signaling_thread_.get(); |
| 111 | } |
| 112 | |
| 113 | std::shared_ptr<MediaStreamTrack> RtcRuntime::get_or_create_media_stream_track( |
| 114 | webrtc::scoped_refptr<webrtc::MediaStreamTrackInterface> rtc_track) { |
| 115 | webrtc::MutexLock lock(&mutex_); |
| 116 | for (std::weak_ptr<MediaStreamTrack> weak_existing_track : |
| 117 | media_stream_tracks_) { |
| 118 | if (std::shared_ptr<MediaStreamTrack> existing_track = |
| 119 | weak_existing_track.lock()) { |
| 120 | if (existing_track->rtc_track() == rtc_track) { |
| 121 | return existing_track; |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | if (rtc_track->kind() == webrtc::MediaStreamTrackInterface::kVideoKind) { |
| 127 | std::shared_ptr<VideoTrack> video_track = |
| 128 | std::shared_ptr<VideoTrack>(new VideoTrack( |
| 129 | shared_from_this(), |
| 130 | webrtc::scoped_refptr<webrtc::VideoTrackInterface>( |
| 131 | static_cast<webrtc::VideoTrackInterface*>(rtc_track.get())))); |
| 132 | |
| 133 | media_stream_tracks_.push_back( |
| 134 | std::static_pointer_cast<MediaStreamTrack>(video_track)); |
| 135 | return video_track; |
| 136 | } else { |
| 137 | std::shared_ptr<AudioTrack> audio_track = |
| 138 | std::shared_ptr<AudioTrack>(new AudioTrack( |
| 139 | shared_from_this(), |
| 140 | webrtc::scoped_refptr<webrtc::AudioTrackInterface>( |
| 141 | static_cast<webrtc::AudioTrackInterface*>(rtc_track.get())))); |
| 142 | |
| 143 | media_stream_tracks_.push_back( |
| 144 | std::static_pointer_cast<MediaStreamTrack>(audio_track)); |
| 145 | return audio_track; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | std::shared_ptr<AudioTrack> RtcRuntime::get_or_create_audio_track( |
| 150 | webrtc::scoped_refptr<webrtc::AudioTrackInterface> track) { |
| 151 | return std::static_pointer_cast<AudioTrack>( |
| 152 | get_or_create_media_stream_track(track)); |
| 153 | } |
| 154 | |
| 155 | std::shared_ptr<VideoTrack> RtcRuntime::get_or_create_video_track( |
| 156 | webrtc::scoped_refptr<webrtc::VideoTrackInterface> track) { |
| 157 | return std::static_pointer_cast<VideoTrack>( |
| 158 | get_or_create_media_stream_track(track)); |
| 159 | } |
| 160 | |
| 161 | LogSink::LogSink( |
| 162 | rust::Fn<void(rust::String message, LoggingSeverity severity)> fnc) |
| 163 | : fnc_(fnc) { |
| 164 | // m150 replaced the old "release builds don't log" default with LoggingConfig, |
| 165 | // which defaults to log_to_stderr=true / debug_severity=LS_INFO and installs |
| 166 | // itself on the first log call. That writes straight to stderr, bypassing this |
| 167 | // sink and therefore the Rust log facade, so nothing downstream can filter it. |
| 168 | // Route everything through the sink only. |
| 169 | webrtc::LogMessage::SetLogToStderr(false); |
| 170 | webrtc::LogMessage::LogToDebug(webrtc::LoggingSeverity::LS_NONE); |
| 171 | |
| 172 | webrtc::LogMessage::AddLogToStream(this, webrtc::LoggingSeverity::LS_VERBOSE); |
| 173 | } |
| 174 | |
| 175 | LogSink::~LogSink() { |
| 176 | webrtc::LogMessage::RemoveLogToStream(this); |
| 177 | } |
| 178 | |
| 179 | void LogSink::OnLogMessage(const std::string& message, |
| 180 | webrtc::LoggingSeverity severity) { |
| 181 | fnc_(rust::String::lossy(message), static_cast<LoggingSeverity>(severity)); |
| 182 | } |
| 183 | |
| 184 | std::unique_ptr<LogSink> new_log_sink( |
| 185 | rust::Fn<void(rust::String, LoggingSeverity)> fnc) { |
| 186 | return std::make_unique<LogSink>(fnc); |
| 187 | } |
| 188 | |
| 189 | rust::String create_random_uuid() { |
| 190 | return webrtc::CreateRandomUuid(); |
| 191 | } |
| 192 | |
| 193 | void tune_windows_camera(rust::Str target) { |
| 194 | #ifdef WEBRTC_WIN |
| 195 | if (target.empty()) { |
| 196 | return; |
| 197 | } |
| 198 | using Microsoft::WRL::ComPtr; |
| 199 | |
| 200 | static const GUID kPropSetVidCapVideoProcAmp = { |
| 201 | 0xC6E13360, |
| 202 | 0x30AC, |
| 203 | 0x11d0, |
| 204 | {0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}}; |
| 205 | static const GUID kPropSetVidCapCameraControl = { |
| 206 | 0xC6E13370, |
| 207 | 0x30AC, |
| 208 | 0x11d0, |
| 209 | {0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}}; |
| 210 | |
| 211 | std::wstring wanted; |
| 212 | if (!target.empty()) { |
| 213 | int wide_len = MultiByteToWideChar(CP_UTF8, 0, target.data(), |
| 214 | static_cast<int>(target.size()), nullptr, |
| 215 | 0); |
| 216 | if (wide_len > 0) { |
| 217 | wanted.resize(wide_len); |
| 218 | MultiByteToWideChar(CP_UTF8, 0, target.data(), |
| 219 | static_cast<int>(target.size()), wanted.data(), |
| 220 | wide_len); |
| 221 | } |
| 222 | } |
| 223 | auto to_lower = [](std::wstring text) { |
| 224 | for (wchar_t& ch : text) { |
| 225 | if (ch >= L'A' && ch <= L'Z') { |
| 226 | ch = static_cast<wchar_t>(ch - L'A' + L'a'); |
| 227 | } |
| 228 | } |
| 229 | return text; |
| 230 | }; |
| 231 | const std::wstring wanted_lower = to_lower(wanted); |
| 232 | if (wanted_lower.empty()) { |
| 233 | return; |
| 234 | } |
| 235 | |
| 236 | HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED); |
| 237 | const bool com_owned = SUCCEEDED(hr_com); |
| 238 | |
| 239 | ComPtr<ICreateDevEnum> dev_enum; |
| 240 | if (SUCCEEDED(CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, |
| 241 | CLSCTX_INPROC_SERVER, |
| 242 | IID_PPV_ARGS(&dev_enum))) && |
| 243 | dev_enum) { |
| 244 | ComPtr<IEnumMoniker> enum_moniker; |
| 245 | if (SUCCEEDED(dev_enum->CreateClassEnumerator( |
| 246 | CLSID_VideoInputDeviceCategory, &enum_moniker, 0)) && |
| 247 | enum_moniker) { |
| 248 | ComPtr<IMoniker> moniker; |
| 249 | ULONG fetched = 0; |
| 250 | while (enum_moniker->Next(1, &moniker, &fetched) == S_OK && moniker) { |
| 251 | bool matches = false; |
| 252 | if (!matches) { |
| 253 | ComPtr<IPropertyBag> bag; |
| 254 | if (SUCCEEDED(moniker->BindToStorage(nullptr, nullptr, |
| 255 | IID_PPV_ARGS(&bag))) && |
| 256 | bag) { |
| 257 | for (const wchar_t* prop : {L"DevicePath", L"FriendlyName"}) { |
| 258 | VARIANT var; |
| 259 | VariantInit(&var); |
| 260 | if (SUCCEEDED(bag->Read(prop, &var, nullptr)) && |
| 261 | var.vt == VT_BSTR && var.bstrVal) { |
| 262 | std::wstring value_lower = to_lower(var.bstrVal); |
| 263 | if (value_lower == wanted_lower || |
| 264 | value_lower.find(wanted_lower) != std::wstring::npos || |
| 265 | wanted_lower.find(value_lower) != std::wstring::npos) { |
| 266 | matches = true; |
| 267 | } |
| 268 | } |
| 269 | VariantClear(&var); |
| 270 | if (matches) { |
| 271 | break; |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | if (matches) { |
| 278 | ComPtr<IBaseFilter> filter; |
| 279 | if (SUCCEEDED(moniker->BindToObject(nullptr, nullptr, |
| 280 | IID_PPV_ARGS(&filter))) && |
| 281 | filter) { |
| 282 | ComPtr<IKsPropertySet> ks; |
| 283 | if (SUCCEEDED(filter.As(&ks)) && ks) { |
| 284 | // 50 Hz anti-flicker (power line frequency = 1) |
| 285 | KSPROPERTY_VIDEOPROCAMP_S powerline = {}; |
| 286 | powerline.Property.Set = kPropSetVidCapVideoProcAmp; |
| 287 | powerline.Property.Id = |
| 288 | KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY; |
| 289 | powerline.Property.Flags = KSPROPERTY_TYPE_SET; |
| 290 | powerline.Value = 1; |
| 291 | powerline.Flags = KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL; |
| 292 | ks->Set(kPropSetVidCapVideoProcAmp, |
| 293 | KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY, |
| 294 | &powerline.Value, |
| 295 | sizeof(powerline) - sizeof(KSPROPERTY), &powerline, |
| 296 | sizeof(powerline)); |
| 297 | |
| 298 | // Disable low-light auto-exposure frame-rate drop |
| 299 | KSPROPERTY_CAMERACONTROL_S priority = {}; |
| 300 | priority.Property.Set = kPropSetVidCapCameraControl; |
| 301 | priority.Property.Id = |
| 302 | KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY; |
| 303 | priority.Property.Flags = KSPROPERTY_TYPE_SET; |
| 304 | priority.Value = 0; |
| 305 | priority.Flags = KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL; |
| 306 | ks->Set(kPropSetVidCapCameraControl, |
| 307 | KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY, |
| 308 | &priority.Value, |
| 309 | sizeof(priority) - sizeof(KSPROPERTY), &priority, |
| 310 | sizeof(priority)); |
| 311 | } |
| 312 | } |
| 313 | moniker.Reset(); |
| 314 | break; |
| 315 | } |
| 316 | moniker.Reset(); |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | if (com_owned) { |
| 322 | CoUninitialize(); |
| 323 | } |
| 324 | #else |
| 325 | (void)target; |
| 326 | #endif |
| 327 | } |
| 328 | |
| 329 | } // namespace livekit_ffi |