| #include "VideoCapturerInterface.h" |
| 6 | #include "CodecSelectHelper.h" |
| 7 | #include "Message.h" |
| 8 | #include "platform/PlatformInterface.h" |
| 9 |
| 10 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 11 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 12 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 13 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 14 | #include "api/task_queue/default_task_queue_factory.h" |
| 15 | #include "media/engine/webrtc_media_engine.h" |
| 16 | #include "system_wrappers/include/field_trial.h" |
| 17 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 18 | #include "call/call.h" |
| 19 | #include "modules/rtp_rtcp/source/rtp_utility.h" |
| 20 | #include "api/call/audio_sink.h" |
| 21 | #include "modules/audio_processing/audio_buffer.h" |
| 22 | #include "modules/audio_device/include/audio_device_factory.h" |
| 23 |
| 24 | namespace tgcalls { |
| 25 | namespace { |
| 26 |
| 27 | constexpr uint32_t ssrcAudioIncoming = 1; |
| 28 | constexpr uint32_t ssrcAudioOutgoing = 2; |
| 29 | constexpr uint32_t ssrcAudioFecIncoming = 5; |
| 30 | constexpr uint32_t ssrcAudioFecOutgoing = 6; |
| 31 | constexpr uint32_t ssrcVideoIncoming = 3; |
| 32 | constexpr uint32_t ssrcVideoOutgoing = 4; |
| 33 | constexpr uint32_t ssrcVideoFecIncoming = 7; |
| 34 | constexpr uint32_t ssrcVideoFecOutgoing = 8; |
| 35 |
| 36 | rtc::Thread *makeWorkerThread() { |
| 37 | static std::unique_ptr<rtc::Thread> value = rtc::Thread::Create(); |
| 38 | value->SetName("WebRTC-Worker", nullptr); |
| 39 | value->Start(); |
| 40 | return value.get(); |
| 41 | } |
| 42 |
| 43 | VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 44 | return videoCapture |
| 45 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 46 | : nullptr; |
| 47 | } |
| 48 |
| 49 | class AudioCaptureAnalyzer : public webrtc::CustomAudioAnalyzer { |
| 50 | private: |
| 51 | void Initialize(int sample_rate_hz, int num_channels) override { |
| 52 |
| 53 | } |
| 54 | // Analyzes the given capture or render signal. |
| 55 | void Analyze(const webrtc::AudioBuffer* audio) override { |
| 56 | _analyze(audio); |
| 57 | } |
| 58 | // Returns a string representation of the module state. |
| 59 | std::string ToString() const override { |
| 60 | return "analyzing"; |
| 61 | } |
| 62 |
| 63 | std::function<void(const webrtc::AudioBuffer*)> _analyze; |
| 64 |
| 65 | public: |
| 66 | AudioCaptureAnalyzer(std::function<void(const webrtc::AudioBuffer*)> analyze) : |
| 67 | _analyze(analyze) { |
| 68 | } |
| 69 |
| 70 | virtual ~AudioCaptureAnalyzer() = default; |
| 71 | }; |
| 72 |
| 73 |
| 74 | } // namespace |
| 75 |
| 76 | class VideoSinkInterfaceProxyImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 77 | public: |
| 78 | VideoSinkInterfaceProxyImpl(bool rewriteRotation) : |
| 79 | _rewriteRotation(rewriteRotation) { |
| 80 | } |
| 81 |
| 82 | virtual ~VideoSinkInterfaceProxyImpl() { |
| 83 | } |
| 84 |
| 85 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 86 | if (_impl) { |
| 87 | if (_rewriteRotation) { |
| 88 | webrtc::VideoFrame updatedFrame = frame; |
| 89 | //updatedFrame.set_rotation(webrtc::VideoRotation::kVideoRotation_90); |
| 90 | _impl->OnFrame(updatedFrame); |
| 91 | } else { |
| 92 | _impl->OnFrame(frame); |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 |
| 97 | virtual void OnDiscardedFrame() override { |
| 98 | if (_impl) { |
| 99 | _impl->OnDiscardedFrame(); |
| 100 | } |
| 101 | } |
| 102 |
| 103 | void setSink(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 104 | _impl = impl; |
| 105 | } |
| 106 |
| 107 | private: |
| 108 | bool _rewriteRotation = false; |
| 109 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _impl; |
| 110 |
| 111 | }; |
| 112 |
| 113 | class AudioTrackSinkInterfaceImpl: public webrtc::AudioSinkInterface { |
| 114 | private: |
| 115 | std::function<void(float)> _update; |
| 116 |
| 117 | int _peakCount = 0; |
| 118 | uint16_t _peak = 0; |
| 119 |
| 120 | public: |
| 121 | AudioTrackSinkInterfaceImpl(std::function<void(float)> update) : |
| 122 | _update(update) { |
| 123 | } |
| 124 |
| 125 | virtual ~AudioTrackSinkInterfaceImpl() { |
| 126 | } |
| 127 |
| 128 | virtual void OnData(const Data& audio) override { |
| 129 | if (audio.channels == 1) { |
| 130 | int16_t *samples = (int16_t *)audio.data; |
| 131 | int numberOfSamplesInFrame = (int)audio.samples_per_channel; |
| 132 |
| 133 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 134 | int16_t sample = samples[i]; |
| 135 | if (sample < 0) { |
| 136 | sample = -sample; |
| 137 | } |
| 138 | if (_peak < sample) { |
| 139 | _peak = sample; |
| 140 | } |
| 141 | _peakCount += 1; |
| 142 | } |
| 143 |
| 144 | if (_peakCount >= 1200) { |
| 145 | float level = ((float)(_peak)) / 4000.0f; |
| 146 | _peak = 0; |
| 147 | _peakCount = 0; |
| 148 | _update(level); |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | }; |
| 153 |
| 154 | rtc::Thread *MediaManager::getWorkerThread() { |
| 155 | static rtc::Thread *value = makeWorkerThread(); |
| 156 | return value; |
| 157 | } |
| 158 |
| 159 | MediaManager::MediaManager( |
| 160 | rtc::Thread *thread, |
| 161 | bool isOutgoing, |
| 162 | ProtocolVersion protocolVersion, |
| 163 | const MediaDevicesConfig &devicesConfig, |
| 164 | std::shared_ptr<VideoCaptureInterface> videoCapture, |
| 165 | std::function<void(Message &&)> sendSignalingMessage, |
| 166 | std::function<void(Message &&)> sendTransportMessage, |
| 167 | std::function<void(int)> signalBarsUpdated, |
| 168 | std::function<void(float)> audioLevelUpdated, |
| 169 | bool enableHighBitrateVideo, |
| 170 | std::vector<std::string> preferredCodecs, |
| 171 | std::shared_ptr<PlatformContext> platformContext) : |
| 172 | _thread(thread), |
| 173 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 174 | _taskQueueFactory(webrtc::CreateDefaultTaskQueueFactory()), |
| 175 | _sendSignalingMessage(std::move(sendSignalingMessage)), |
| 176 | _sendTransportMessage(std::move(sendTransportMessage)), |
| 177 | _signalBarsUpdated(std::move(signalBarsUpdated)), |
| 178 | _audioLevelUpdated(std::move(audioLevelUpdated)), |
| 179 | _protocolVersion(protocolVersion), |
| 180 | _outgoingVideoState(videoCapture ? VideoState::Active : VideoState::Inactive), |
| 181 | _videoCapture(std::move(videoCapture)), |
| 182 | _enableHighBitrateVideo(enableHighBitrateVideo), |
| 183 | _platformContext(platformContext) { |
| 184 | bool rewriteFrameRotation = false; |
| 185 | switch (_protocolVersion) { |
| 186 | case ProtocolVersion::V0: |
| 187 | rewriteFrameRotation = true; |
| 188 | break; |
| 189 | case ProtocolVersion::V1: |
| 190 | rewriteFrameRotation = false; |
| 191 | break; |
| 192 | default: |
| 193 | break; |
| 194 | } |
| 195 | _incomingVideoSinkProxy.reset(new VideoSinkInterfaceProxyImpl(rewriteFrameRotation)); |
| 196 |
| 197 | _ssrcAudio.incoming = isOutgoing ? ssrcAudioIncoming : ssrcAudioOutgoing; |
| 198 | _ssrcAudio.outgoing = (!isOutgoing) ? ssrcAudioIncoming : ssrcAudioOutgoing; |
| 199 | _ssrcAudio.fecIncoming = isOutgoing ? ssrcAudioFecIncoming : ssrcAudioFecOutgoing; |
| 200 | _ssrcAudio.fecOutgoing = (!isOutgoing) ? ssrcAudioFecIncoming : ssrcAudioFecOutgoing; |
| 201 | _ssrcVideo.incoming = isOutgoing ? ssrcVideoIncoming : ssrcVideoOutgoing; |
| 202 | _ssrcVideo.outgoing = (!isOutgoing) ? ssrcVideoIncoming : ssrcVideoOutgoing; |
| 203 | _ssrcVideo.fecIncoming = isOutgoing ? ssrcVideoFecIncoming : ssrcVideoFecOutgoing; |
| 204 | _ssrcVideo.fecOutgoing = (!isOutgoing) ? ssrcVideoFecIncoming : ssrcVideoFecOutgoing; |
| 205 |
| 206 | _audioNetworkInterface = std::unique_ptr<MediaManager::NetworkInterfaceImpl>(new MediaManager::NetworkInterfaceImpl(this, false)); |
| 207 | _videoNetworkInterface = std::unique_ptr<MediaManager::NetworkInterfaceImpl>(new MediaManager::NetworkInterfaceImpl(this, true)); |
| 208 |
| 209 | webrtc::field_trial::InitFieldTrialsFromString( |
| 210 | "WebRTC-Audio-SendSideBwe/Enabled/" |
| 211 | "WebRTC-Audio-Allocation/min:6kbps,max:32kbps/" |
| 212 | "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 213 | "WebRTC-FlexFEC-03/Enabled/" |
| 214 | "WebRTC-FlexFEC-03-Advertised/Enabled/" |
| 215 | ); |
| 216 |
| 217 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 218 |
| 219 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 220 |
| 221 | cricket::MediaEngineDependencies mediaDeps; |
| 222 | mediaDeps.task_queue_factory = _taskQueueFactory.get(); |
| 223 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>(); |
| 224 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>(); |
| 225 |
| 226 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext); |
| 227 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 228 |
| 229 | _myVideoFormats = ComposeSupportedFormats( |
| 230 | mediaDeps.video_encoder_factory->GetSupportedFormats(), |
| 231 | mediaDeps.video_decoder_factory->GetSupportedFormats(), |
| 232 | preferredCodecs, |
| 233 | _platformContext); |
| 234 |
| 235 | // [this] should outlive the analyzer |
| 236 | auto analyzer = new AudioCaptureAnalyzer([this](const webrtc::AudioBuffer* buffer) { |
| 237 | if (!buffer) { |
| 238 | return; |
| 239 | } |
| 240 | if (buffer->num_channels() != 1) { |
| 241 | return; |
| 242 | } |
| 243 |
| 244 | float peak = 0; |
| 245 | int peakCount = 0; |
| 246 | const float *samples = buffer->channels_const()[0]; |
| 247 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 248 | float sample = samples[i]; |
| 249 | if (sample < 0) { |
| 250 | sample = -sample; |
| 251 | } |
| 252 | if (peak < sample) { |
| 253 | peak = sample; |
| 254 | } |
| 255 | peakCount += 1; |
| 256 | } |
| 257 |
| 258 | this->_thread->PostTask(RTC_FROM_HERE, [this, peak, peakCount](){ |
| 259 | auto strong = this; |
| 260 |
| 261 | strong->_myAudioLevelPeakCount += peakCount; |
| 262 | if (strong->_myAudioLevelPeak < peak) { |
| 263 | strong->_myAudioLevelPeak = peak; |
| 264 | } |
| 265 | if (strong->_myAudioLevelPeakCount >= 1200) { |
| 266 | float level = strong->_myAudioLevelPeak / 4000.0f; |
| 267 | strong->_myAudioLevelPeak = 0; |
| 268 | strong->_myAudioLevelPeakCount = 0; |
| 269 | strong->_currentMyAudioLevel = level; |
| 270 | } |
| 271 | }); |
| 272 | }); |
| 273 |
| 274 | webrtc::AudioProcessingBuilder builder; |
| 275 | builder.SetCaptureAnalyzer(std::unique_ptr<AudioCaptureAnalyzer>(analyzer)); |
| 276 |
| 277 | mediaDeps.audio_processing = builder.Create(); |
| 278 |
| 279 | /*_audioDeviceModule = createAudioDeviceModule(); |
| 280 | if (!_audioDeviceModule) { |
| 281 | return; |
| 282 | } |
| 283 | mediaDeps.adm = _audioDeviceModule;*/ |
| 284 |
| 285 | _mediaEngine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 286 | _mediaEngine->Init(); |
| 287 |
| 288 | /*setAudioInputDevice(devicesConfig.audioInputId); |
| 289 | setAudioOutputDevice(devicesConfig.audioOutputId); |
| 290 | setInputVolume(devicesConfig.inputVolume); |
| 291 | setOutputVolume(devicesConfig.outputVolume);*/ |
| 292 |
| 293 | webrtc::Call::Config callConfig(_eventLog.get()); |
| 294 | callConfig.task_queue_factory = _taskQueueFactory.get(); |
| 295 | callConfig.trials = &_fieldTrials; |
| 296 | callConfig.audio_state = _mediaEngine->voice().GetAudioState(); |
| 297 | _call.reset(webrtc::Call::Create(callConfig)); |
| 298 |
| 299 | cricket::AudioOptions audioOptions; |
| 300 | audioOptions.echo_cancellation = true; |
| 301 | audioOptions.noise_suppression = true; |
| 302 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 303 |
| 304 | std::vector<std::string> streamIds; |
| 305 | streamIds.push_back("1"); |
| 306 |
| 307 | _audioChannel.reset(_mediaEngine->voice().CreateMediaChannel(_call.get(), cricket::MediaConfig(), audioOptions, webrtc::CryptoOptions::NoGcm())); |
| 308 | _videoChannel.reset(_mediaEngine->video().CreateMediaChannel(_call.get(), cricket::MediaConfig(), cricket::VideoOptions(), webrtc::CryptoOptions::NoGcm(), _videoBitrateAllocatorFactory.get())); |
| 309 |
| 310 | const uint32_t opusClockrate = 48000; |
| 311 | const uint16_t opusSdpPayload = 111; |
| 312 | const char *opusSdpName = "opus"; |
| 313 | const uint8_t opusSdpChannels = 2; |
| 314 | const uint32_t opusSdpBitrate = 0; |
| 315 |
| 316 | const uint8_t opusMinBitrateKbps = 6; |
| 317 | const uint8_t opusMaxBitrateKbps = 32; |
| 318 | const uint8_t opusStartBitrateKbps = 8; |
| 319 | const uint8_t opusPTimeMs = 120; |
| 320 |
| 321 | cricket::AudioCodec opusCodec(opusSdpPayload, opusSdpName, opusClockrate, opusSdpBitrate, opusSdpChannels); |
| 322 | opusCodec.AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc)); |
| 323 | opusCodec.SetParam(cricket::kCodecParamMinBitrate, opusMinBitrateKbps); |
| 324 | opusCodec.SetParam(cricket::kCodecParamStartBitrate, opusStartBitrateKbps); |
| 325 | opusCodec.SetParam(cricket::kCodecParamMaxBitrate, opusMaxBitrateKbps); |
| 326 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 327 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 328 |
| 329 | cricket::AudioSendParameters audioSendPrameters; |
| 330 | audioSendPrameters.codecs.push_back(opusCodec); |
| 331 | audioSendPrameters.extensions.emplace_back(webrtc::RtpExtension::kTransportSequenceNumberUri, 1); |
| 332 | audioSendPrameters.options.echo_cancellation = true; |
| 333 | //audioSendPrameters.options.experimental_ns = false; |
| 334 | audioSendPrameters.options.noise_suppression = true; |
| 335 | audioSendPrameters.options.auto_gain_control = true; |
| 336 | //audioSendPrameters.options.highpass_filter = false; |
| 337 | audioSendPrameters.options.typing_detection = false; |
| 338 | //audioSendPrameters.max_bandwidth_bps = 16000; |
| 339 | audioSendPrameters.rtcp.reduced_size = true; |
| 340 | audioSendPrameters.rtcp.remote_estimate = true; |
| 341 | _audioChannel->SetSendParameters(audioSendPrameters); |
| 342 | _audioChannel->AddSendStream(cricket::StreamParams::CreateLegacy(_ssrcAudio.outgoing)); |
| 343 | _audioChannel->SetInterface(_audioNetworkInterface.get()); |
| 344 |
| 345 | cricket::AudioRecvParameters audioRecvParameters; |
| 346 | audioRecvParameters.codecs.emplace_back(opusSdpPayload, opusSdpName, opusClockrate, opusSdpBitrate, opusSdpChannels); |
| 347 | audioRecvParameters.extensions.emplace_back(webrtc::RtpExtension::kTransportSequenceNumberUri, 1); |
| 348 | audioRecvParameters.rtcp.reduced_size = true; |
| 349 | audioRecvParameters.rtcp.remote_estimate = true; |
| 350 |
| 351 | _audioChannel->SetRecvParameters(audioRecvParameters); |
| 352 | cricket::StreamParams audioRecvStreamParams = cricket::StreamParams::CreateLegacy(_ssrcAudio.incoming); |
| 353 | audioRecvStreamParams.set_stream_ids(streamIds); |
| 354 | _audioChannel->AddRecvStream(audioRecvStreamParams); |
| 355 | _audioChannel->SetPlayout(true); |
| 356 |
| 357 | _videoChannel->SetInterface(_videoNetworkInterface.get()); |
| 358 |
| 359 | adjustBitratePreferences(true); |
| 360 | } |
| 361 |
| 362 | rtc::scoped_refptr<webrtc::AudioDeviceModule> MediaManager::createAudioDeviceModule() { |
| 363 | const auto check = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 364 | auto result = webrtc::AudioDeviceModule::Create( |
| 365 | layer, |
| 366 | _taskQueueFactory.get()); |
| 367 | return (result && (result->Init() == 0)) ? result : nullptr; |
| 368 | }; |
| 369 | #ifdef WEBRTC_WIN |
| 370 | if (auto result = webrtc::CreateWindowsCoreAudioAudioDeviceModule(_taskQueueFactory.get())) { |
| 371 | if (result->Init() == 0) { |
| 372 | return result; |
| 373 | } |
| 374 | } |
| 375 | #endif // WEBRTC_WIN |
| 376 | if (auto result = check(webrtc::AudioDeviceModule::kPlatformDefaultAudio)) { |
| 377 | return result; |
| 378 | #ifdef WEBRTC_LINUX |
| 379 | } else if (auto result = check(webrtc::AudioDeviceModule::kLinuxAlsaAudio)) { |
| 380 | return result; |
| 381 | #endif // WEBRTC_LINUX |
| 382 | } |
| 383 | return nullptr; |
| 384 | } |
| 385 |
| 386 | void MediaManager::start() { |
| 387 | const auto weak = std::weak_ptr<MediaManager>(shared_from_this()); |
| 388 |
| 389 | // Here we hope that thread outlives the sink |
| 390 | rtc::Thread *thread = _thread; |
| 391 | std::unique_ptr<AudioTrackSinkInterfaceImpl> incomingSink(new AudioTrackSinkInterfaceImpl([weak, thread](float level) { |
| 392 | thread->PostTask(RTC_FROM_HERE, [weak, level] { |
| 393 | if (const auto strong = weak.lock()) { |
| 394 | strong->_currentAudioLevel = level; |
| 395 | } |
| 396 | }); |
| 397 | })); |
| 398 | _audioChannel->SetRawAudioSink(_ssrcAudio.incoming, std::move(incomingSink)); |
| 399 |
| 400 | _sendSignalingMessage({ _myVideoFormats }); |
| 401 |
| 402 | if (_videoCapture != nullptr) { |
| 403 | setSendVideo(_videoCapture); |
| 404 | } |
| 405 |
| 406 | beginStatsTimer(3000); |
| 407 | if (_audioLevelUpdated != nullptr) { |
| 408 | beginLevelsTimer(50); |
| 409 | } |
| 410 | } |
| 411 |
| 412 | MediaManager::~MediaManager() { |
| 413 | assert(_thread->IsCurrent()); |
| 414 |
| 415 | RTC_LOG(LS_INFO) << "MediaManager::~MediaManager()"; |
| 416 |
| 417 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkDown); |
| 418 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkDown); |
| 419 |
| 420 | _audioChannel->OnReadyToSend(false); |
| 421 | _audioChannel->SetSend(false); |
| 422 | _audioChannel->SetAudioSend(_ssrcAudio.outgoing, false, nullptr, &_audioSource); |
| 423 |
| 424 | _audioChannel->SetPlayout(false); |
| 425 |
| 426 | _audioChannel->RemoveRecvStream(_ssrcAudio.incoming); |
| 427 | _audioChannel->RemoveSendStream(_ssrcAudio.outgoing); |
| 428 |
| 429 | _audioChannel->SetInterface(nullptr); |
| 430 |
| 431 | setSendVideo(nullptr); |
| 432 |
| 433 | if (computeIsReceivingVideo()) { |
| 434 | _videoChannel->RemoveRecvStream(_ssrcVideo.incoming); |
| 435 | if (_enableFlexfec) { |
| 436 | _videoChannel->RemoveRecvStream(_ssrcVideo.fecIncoming); |
| 437 | } |
| 438 | } |
| 439 |
| 440 | if (_didConfigureVideo) { |
| 441 | _videoChannel->OnReadyToSend(false); |
| 442 | _videoChannel->SetSend(false); |
| 443 |
| 444 | if (_enableFlexfec) { |
| 445 | _videoChannel->RemoveSendStream(_ssrcVideo.outgoing); |
| 446 | _videoChannel->RemoveSendStream(_ssrcVideo.fecOutgoing); |
| 447 | } else { |
| 448 | _videoChannel->RemoveSendStream(_ssrcVideo.outgoing); |
| 449 | } |
| 450 | } |
| 451 |
| 452 | _videoChannel->SetInterface(nullptr); |
| 453 | } |
| 454 |
| 455 | void MediaManager::setIsConnected(bool isConnected) { |
| 456 | if (_isConnected == isConnected) { |
| 457 | return; |
| 458 | } |
| 459 | bool isFirstConnection = false; |
| 460 | if (!_isConnected && isConnected) { |
| 461 | _didConnectOnce = true; |
| 462 | isFirstConnection = true; |
| 463 | } |
| 464 | _isConnected = isConnected; |
| 465 |
| 466 | if (_isConnected) { |
| 467 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkUp); |
| 468 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkUp); |
| 469 | } else { |
| 470 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkDown); |
| 471 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkDown); |
| 472 | } |
| 473 | if (_audioChannel) { |
| 474 | _audioChannel->OnReadyToSend(_isConnected); |
| 475 | _audioChannel->SetSend(_isConnected); |
| 476 | _audioChannel->SetAudioSend(_ssrcAudio.outgoing, _isConnected && (_outgoingAudioState == AudioState::Active), nullptr, &_audioSource); |
| 477 | } |
| 478 | if (computeIsSendingVideo() && _videoChannel) { |
| 479 | _videoChannel->OnReadyToSend(_isConnected); |
| 480 | _videoChannel->SetSend(_isConnected); |
| 481 | } |
| 482 | if (isFirstConnection) { |
| 483 | sendVideoParametersMessage(); |
| 484 | sendOutgoingMediaStateMessage(); |
| 485 | } |
| 486 | } |
| 487 |
| 488 | void MediaManager::sendVideoParametersMessage() { |
| 489 | const auto aspectRatioValue = uint32_t(_localPreferredVideoAspectRatio * 1000.0); |
| 490 | _sendTransportMessage({ VideoParametersMessage{ aspectRatioValue } }); |
| 491 | } |
| 492 |
| 493 | void MediaManager::sendOutgoingMediaStateMessage() { |
| 494 | _sendTransportMessage({ RemoteMediaStateMessage{ _outgoingAudioState, _outgoingVideoState } }); |
| 495 | } |
| 496 |
| 497 | void MediaManager::beginStatsTimer(int timeoutMs) { |
| 498 | const auto weak = std::weak_ptr<MediaManager>(shared_from_this()); |
| 499 | _thread->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 500 | auto strong = weak.lock(); |
| 501 | if (!strong) { |
| 502 | return; |
| 503 | } |
| 504 | strong->collectStats(); |
| 505 | }, timeoutMs); |
| 506 | } |
| 507 |
| 508 | void MediaManager::beginLevelsTimer(int timeoutMs) { |
| 509 | const auto weak = std::weak_ptr<MediaManager>(shared_from_this()); |
| 510 | _thread->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 511 | auto strong = weak.lock(); |
| 512 | if (!strong) { |
| 513 | return; |
| 514 | } |
| 515 |
| 516 | float effectiveLevel = fmaxf(strong->_currentAudioLevel, strong->_currentMyAudioLevel); |
| 517 | strong->_audioLevelUpdated(effectiveLevel); |
| 518 |
| 519 | strong->beginLevelsTimer(50); |
| 520 | }, timeoutMs); |
| 521 | } |
| 522 |
| 523 | void MediaManager::collectStats() { |
| 524 | auto stats = _call->GetStats(); |
| 525 | float bitrateNorm = 16.0f; |
| 526 | switch (_outgoingVideoState) { |
| 527 | case VideoState::Active: |
| 528 | bitrateNorm = 600.0f; |
| 529 | break; |
| 530 | default: |
| 531 | break; |
| 532 | } |
| 533 | float sendBitrateKbps = ((float)stats.send_bandwidth_bps / 1000.0f); |
| 534 |
| 535 | RTC_LOG(LS_INFO) << "MediaManager sendBitrateKbps=" << (stats.send_bandwidth_bps / 1000); |
| 536 |
| 537 | float signalBarsNorm = 4.0f; |
| 538 | float adjustedQuality = sendBitrateKbps / bitrateNorm; |
| 539 | adjustedQuality = fmaxf(0.0f, adjustedQuality); |
| 540 | adjustedQuality = fminf(1.0f, adjustedQuality); |
| 541 | if (_signalBarsUpdated) { |
| 542 | _signalBarsUpdated((int)(adjustedQuality * signalBarsNorm)); |
| 543 | } |
| 544 |
| 545 | _bitrateRecords.push_back(CallStatsBitrateRecord { (int32_t)(rtc::TimeMillis() / 1000), stats.send_bandwidth_bps / 1000 }); |
| 546 |
| 547 | beginStatsTimer(2000); |
| 548 | } |
| 549 |
| 550 | void MediaManager::notifyPacketSent(const rtc::SentPacket &sentPacket) { |
| 551 | _call->OnSentPacket(sentPacket); |
| 552 | } |
| 553 |
| 554 | void MediaManager::setPeerVideoFormats(VideoFormatsMessage &&peerFormats) { |
| 555 | if (!_videoCodecs.empty()) { |
| 556 | return; |
| 557 | } |
| 558 |
| 559 | bool wasReceivingVideo = computeIsReceivingVideo(); |
| 560 |
| 561 | assert(!_videoCodecOut.has_value()); |
| 562 | auto formats = ComputeCommonFormats( |
| 563 | _myVideoFormats, |
| 564 | std::move(peerFormats)); |
| 565 | auto codecs = AssignPayloadTypesAndDefaultCodecs(std::move(formats)); |
| 566 | if (codecs.myEncoderIndex >= 0) { |
| 567 | assert(codecs.myEncoderIndex < codecs.list.size()); |
| 568 | _videoCodecOut = codecs.list[codecs.myEncoderIndex]; |
| 569 | } |
| 570 | _videoCodecs = std::move(codecs.list); |
| 571 | if (_videoCodecOut.has_value()) { |
| 572 | checkIsSendingVideoChanged(false); |
| 573 | } |
| 574 | if (_videoCodecs.size() != 0) { |
| 575 | checkIsReceivingVideoChanged(wasReceivingVideo); |
| 576 | } |
| 577 | } |
| 578 |
| 579 | bool MediaManager::videoCodecsNegotiated() const { |
| 580 | return !_videoCodecs.empty(); |
| 581 | } |
| 582 |
| 583 | bool MediaManager::computeIsSendingVideo() const { |
| 584 | return _videoCapture != nullptr && _videoCodecOut.has_value(); |
| 585 | } |
| 586 |
| 587 | bool MediaManager::computeIsReceivingVideo() const { |
| 588 | return _videoCodecs.size() != 0; |
| 589 | } |
| 590 |
| 591 | void MediaManager::setSendVideo(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 592 | const auto wasSending = computeIsSendingVideo(); |
| 593 | const auto wasReceiving = computeIsReceivingVideo(); |
| 594 |
| 595 | if (_videoCapture) { |
| 596 | GetVideoCaptureAssumingSameThread(_videoCapture.get())->setStateUpdated(nullptr); |
| 597 | } |
| 598 | _videoCapture = videoCapture; |
| 599 | if (_videoCapture) { |
| 600 | _videoCapture->setPreferredAspectRatio(_preferredAspectRatio); |
| 601 |
| 602 | const auto thread = _thread; |
| 603 | const auto weak = std::weak_ptr<MediaManager>(shared_from_this()); |
| 604 | GetVideoCaptureAssumingSameThread(_videoCapture.get())->setStateUpdated([=](VideoState state) { |
| 605 | thread->PostTask(RTC_FROM_HERE, [=] { |
| 606 | if (const auto strong = weak.lock()) { |
| 607 | strong->setOutgoingVideoState(state); |
| 608 | } |
| 609 | }); |
| 610 | }); |
| 611 | setOutgoingVideoState(VideoState::Active); |
| 612 | } else { |
| 613 | setOutgoingVideoState(VideoState::Inactive); |
| 614 | } |
| 615 |
| 616 | checkIsSendingVideoChanged(wasSending); |
| 617 | checkIsReceivingVideoChanged(wasReceiving); |
| 618 | } |
| 619 |
| 620 | void MediaManager::setRequestedVideoAspect(float aspect) { |
| 621 | if (_localPreferredVideoAspectRatio != aspect) { |
| 622 | _localPreferredVideoAspectRatio = aspect; |
| 623 | if (_didConnectOnce) { |
| 624 | sendVideoParametersMessage(); |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 |
| 629 | void MediaManager::configureSendingVideoIfNeeded() { |
| 630 | if (_didConfigureVideo) { |
| 631 | return; |
| 632 | } |
| 633 | if (!_videoCodecOut.has_value()) { |
| 634 | return; |
| 635 | } |
| 636 | _didConfigureVideo = true; |
| 637 |
| 638 | auto codec = *_videoCodecOut; |
| 639 |
| 640 | codec.SetParam(cricket::kCodecParamMinBitrate, 64); |
| 641 | codec.SetParam(cricket::kCodecParamStartBitrate, 400); |
| 642 | codec.SetParam(cricket::kCodecParamMaxBitrate, _enableHighBitrateVideo ? 2000 : 800); |
| 643 |
| 644 | cricket::VideoSendParameters videoSendParameters; |
| 645 | videoSendParameters.codecs.push_back(codec); |
| 646 |
| 647 | if (_enableFlexfec) { |
| 648 | for (auto &c : _videoCodecs) { |
| 649 | if (c.name == cricket::kFlexfecCodecName) { |
| 650 | videoSendParameters.codecs.push_back(c); |
| 651 | break; |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 |
| 656 | videoSendParameters.extensions.emplace_back(webrtc::RtpExtension::kTransportSequenceNumberUri, 2); |
| 657 | switch (_protocolVersion) { |
| 658 | case ProtocolVersion::V1: |
| 659 | videoSendParameters.extensions.emplace_back(webrtc::RtpExtension::kVideoRotationUri, 3); |
| 660 | videoSendParameters.extensions.emplace_back( |
| 661 | webrtc::RtpExtension::kTimestampOffsetUri, 4); |
| 662 | break; |
| 663 | default: |
| 664 | break; |
| 665 | } |
| 666 | videoSendParameters.rtcp.remote_estimate = true; |
| 667 | _videoChannel->SetSendParameters(videoSendParameters); |
| 668 |
| 669 | if (_enableFlexfec) { |
| 670 | cricket::StreamParams videoSendStreamParams; |
| 671 | cricket::SsrcGroup videoSendSsrcGroup(cricket::kFecFrSsrcGroupSemantics, {_ssrcVideo.outgoing, _ssrcVideo.fecOutgoing}); |
| 672 | videoSendStreamParams.ssrcs = {_ssrcVideo.outgoing}; |
| 673 | videoSendStreamParams.ssrc_groups.push_back(videoSendSsrcGroup); |
| 674 | videoSendStreamParams.cname = "cname"; |
| 675 | _videoChannel->AddSendStream(videoSendStreamParams); |
| 676 | } else { |
| 677 | _videoChannel->AddSendStream(cricket::StreamParams::CreateLegacy(_ssrcVideo.outgoing)); |
| 678 | } |
| 679 |
| 680 | adjustBitratePreferences(true); |
| 681 | } |
| 682 |
| 683 | void MediaManager::checkIsSendingVideoChanged(bool wasSending) { |
| 684 | const auto sending = computeIsSendingVideo(); |
| 685 | if (sending == wasSending) { |
| 686 | return; |
| 687 | } else if (sending) { |
| 688 | configureSendingVideoIfNeeded(); |
| 689 |
| 690 | if (_enableFlexfec) { |
| 691 | _videoChannel->SetVideoSend(_ssrcVideo.outgoing, NULL, GetVideoCaptureAssumingSameThread(_videoCapture.get())->source()); |
| 692 | _videoChannel->SetVideoSend(_ssrcVideo.fecOutgoing, NULL, nullptr); |
| 693 | } else { |
| 694 | _videoChannel->SetVideoSend(_ssrcVideo.outgoing, NULL, GetVideoCaptureAssumingSameThread(_videoCapture.get())->source()); |
| 695 | } |
| 696 |
| 697 | _videoChannel->OnReadyToSend(_isConnected); |
| 698 | _videoChannel->SetSend(_isConnected); |
| 699 | } else { |
| 700 | _videoChannel->SetVideoSend(_ssrcVideo.outgoing, NULL, nullptr); |
| 701 | _videoChannel->SetVideoSend(_ssrcVideo.fecOutgoing, NULL, nullptr); |
| 702 | } |
| 703 |
| 704 | adjustBitratePreferences(true); |
| 705 | } |
| 706 |
| 707 | int MediaManager::getMaxVideoBitrate() const { |
| 708 | return (_enableHighBitrateVideo && _isLowCostNetwork) ? 2000000 : 800000; |
| 709 | } |
| 710 |
| 711 | int MediaManager::getMaxAudioBitrate() const { |
| 712 | if (_isDataSavingActive) { |
| 713 | return 16000; |
| 714 | } else { |
| 715 | return 32000; |
| 716 | } |
| 717 | } |
| 718 |
| 719 | void MediaManager::adjustBitratePreferences(bool resetStartBitrate) { |
| 720 | if (computeIsSendingVideo()) { |
| 721 | webrtc::BitrateConstraints preferences; |
| 722 | preferences.min_bitrate_bps = 64000; |
| 723 | if (resetStartBitrate) { |
| 724 | preferences.start_bitrate_bps = 400000; |
| 725 | } |
| 726 | preferences.max_bitrate_bps = getMaxVideoBitrate(); |
| 727 |
| 728 | _call->GetTransportControllerSend()->SetSdpBitrateParameters(preferences); |
| 729 | } else { |
| 730 | webrtc::BitrateConstraints preferences; |
| 731 | if (_didConfigureVideo) { |
| 732 | // After we have configured outgoing video, RTCP stops working for outgoing audio |
| 733 | // TODO: investigate |
| 734 | preferences.min_bitrate_bps = 16000; |
| 735 | if (resetStartBitrate) { |
| 736 | preferences.start_bitrate_bps = 16000; |
| 737 | } |
| 738 | preferences.max_bitrate_bps = 32000; |
| 739 | } else { |
| 740 | preferences.min_bitrate_bps = 8000; |
| 741 | if (resetStartBitrate) { |
| 742 | preferences.start_bitrate_bps = 16000; |
| 743 | } |
| 744 | preferences.max_bitrate_bps = getMaxAudioBitrate(); |
| 745 | } |
| 746 |
| 747 | _call->GetTransportControllerSend()->SetSdpBitrateParameters(preferences); |
| 748 | } |
| 749 | } |
| 750 |
| 751 | void MediaManager::checkIsReceivingVideoChanged(bool wasReceiving) { |
| 752 | const auto receiving = computeIsReceivingVideo(); |
| 753 | if (receiving == wasReceiving) { |
| 754 | return; |
| 755 | } else { |
| 756 | cricket::VideoRecvParameters videoRecvParameters; |
| 757 |
| 758 | const auto codecs = { |
| 759 | cricket::kFlexfecCodecName, |
| 760 | cricket::kH264CodecName, |
| 761 | cricket::kH265CodecName, |
| 762 | cricket::kVp8CodecName, |
| 763 | cricket::kVp9CodecName, |
| 764 | cricket::kAv1CodecName, |
| 765 | }; |
| 766 | for (const auto &c : _videoCodecs) { |
| 767 | for (const auto known : codecs) { |
| 768 | if (c.name == known) { |
| 769 | videoRecvParameters.codecs.push_back(c); |
| 770 | break; |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 |
| 775 | videoRecvParameters.extensions.emplace_back(webrtc::RtpExtension::kTransportSequenceNumberUri, 2); |
| 776 | switch (_protocolVersion) { |
| 777 | case ProtocolVersion::V1: |
| 778 | videoRecvParameters.extensions.emplace_back(webrtc::RtpExtension::kVideoRotationUri, 3); |
| 779 | videoRecvParameters.extensions.emplace_back( |
| 780 | webrtc::RtpExtension::kTimestampOffsetUri, 4); |
| 781 | break; |
| 782 | default: |
| 783 | break; |
| 784 | } |
| 785 | videoRecvParameters.rtcp.reduced_size = true; |
| 786 | videoRecvParameters.rtcp.remote_estimate = true; |
| 787 |
| 788 | cricket::StreamParams videoRecvStreamParams; |
| 789 | cricket::SsrcGroup videoRecvSsrcGroup(cricket::kFecFrSsrcGroupSemantics, {_ssrcVideo.incoming, _ssrcVideo.fecIncoming}); |
| 790 | videoRecvStreamParams.ssrcs = {_ssrcVideo.incoming}; |
| 791 | videoRecvStreamParams.ssrc_groups.push_back(videoRecvSsrcGroup); |
| 792 | videoRecvStreamParams.cname = "cname"; |
| 793 | std::vector<std::string> streamIds; |
| 794 | streamIds.push_back("1"); |
| 795 | videoRecvStreamParams.set_stream_ids(streamIds); |
| 796 |
| 797 | _videoChannel->SetRecvParameters(videoRecvParameters); |
| 798 | _videoChannel->AddRecvStream(videoRecvStreamParams); |
| 799 | _readyToReceiveVideo = true; |
| 800 | _videoChannel->SetSink(_ssrcVideo.incoming, _incomingVideoSinkProxy.get()); |
| 801 | } |
| 802 | } |
| 803 |
| 804 | void MediaManager::setMuteOutgoingAudio(bool mute) { |
| 805 | setOutgoingAudioState(mute ? AudioState::Muted : AudioState::Active); |
| 806 | _audioChannel->SetAudioSend(_ssrcAudio.outgoing, _isConnected && (_outgoingAudioState == AudioState::Active), nullptr, &_audioSource); |
| 807 | } |
| 808 |
| 809 | void MediaManager::setOutgoingAudioState(AudioState state) { |
| 810 | if (_outgoingAudioState == state) { |
| 811 | return; |
| 812 | } |
| 813 | _outgoingAudioState = state; |
| 814 | sendOutgoingMediaStateMessage(); |
| 815 | } |
| 816 |
| 817 | void MediaManager::setOutgoingVideoState(VideoState state) { |
| 818 | if (_outgoingVideoState == state) { |
| 819 | return; |
| 820 | } |
| 821 | _outgoingVideoState = state; |
| 822 | sendOutgoingMediaStateMessage(); |
| 823 | } |
| 824 |
| 825 | void MediaManager::setIncomingVideoOutput(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 826 | _incomingVideoSinkProxy->setSink(sink); |
| 827 | } |
| 828 |
| 829 | static bool IsRtcp(const uint8_t* packet, size_t length) { |
| 830 | webrtc::RtpUtility::RtpHeaderParser rtp_parser(packet, length); |
| 831 | return rtp_parser.RTCP(); |
| 832 | } |
| 833 |
| 834 | void MediaManager::receiveMessage(DecryptedMessage &&message) { |
| 835 | const auto data = &message.message.data; |
| 836 | if (const auto formats = absl::get_if<VideoFormatsMessage>(data)) { |
| 837 | setPeerVideoFormats(std::move(*formats)); |
| 838 | } else if (const auto audio = absl::get_if<AudioDataMessage>(data)) { |
| 839 | if (IsRtcp(audio->data.data(), audio->data.size())) { |
| 840 | RTC_LOG(LS_VERBOSE) << "Deliver audio RTCP"; |
| 841 | } |
| 842 | _call->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO, audio->data, -1); |
| 843 | } else if (const auto video = absl::get_if<VideoDataMessage>(data)) { |
| 844 | if (_videoChannel) { |
| 845 | if (_readyToReceiveVideo) { |
| 846 | _call->Receiver()->DeliverPacket(webrtc::MediaType::VIDEO, video->data, -1); |
| 847 | } else { |
| 848 | // maybe we need to queue packets for some time? |
| 849 | } |
| 850 | } |
| 851 | } else if (const auto videoParameters = absl::get_if<VideoParametersMessage>(data)) { |
| 852 | float value = ((float)videoParameters->aspectRatio) / 1000.0; |
| 853 | _preferredAspectRatio = value; |
| 854 | if (_videoCapture) { |
| 855 | _videoCapture->setPreferredAspectRatio(value); |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 |
| 860 | void MediaManager::remoteVideoStateUpdated(VideoState videoState) { |
| 861 | switch (videoState) { |
| 862 | case VideoState::Active: |
| 863 | case VideoState::Paused: |
| 864 | configureSendingVideoIfNeeded(); |
| 865 | break; |
| 866 | default: |
| 867 | break; |
| 868 | } |
| 869 | } |
| 870 |
| 871 | void MediaManager::setNetworkParameters(bool isLowCost, bool isDataSavingActive) { |
| 872 | if (_isLowCostNetwork != isLowCost || _isDataSavingActive != isDataSavingActive) { |
| 873 | _isLowCostNetwork = isLowCost; |
| 874 | _isDataSavingActive = isDataSavingActive; |
| 875 | RTC_LOG(LS_INFO) << "MediaManager isLowCostNetwork: " << (isLowCost ? 1 : 0) << ", isDataSavingActive: " << (isDataSavingActive ? 1 : 0); |
| 876 | adjustBitratePreferences(false); |
| 877 | } |
| 878 | } |
| 879 |
| 880 | void MediaManager::fillCallStats(CallStats &callStats) { |
| 881 | if (_videoCodecOut.has_value()) { |
| 882 | callStats.outgoingCodec = _videoCodecOut->name; |
| 883 | } |
| 884 | callStats.bitrateRecords = std::move(_bitrateRecords); |
| 885 | } |
| 886 |
| 887 | void MediaManager::setAudioInputDevice(std::string id) { |
| 888 | const auto recording = _audioDeviceModule->Recording(); |
| 889 | if (recording) { |
| 890 | _audioDeviceModule->StopRecording(); |
| 891 | } |
| 892 | const auto finish = [&] { |
| 893 | if (recording) { |
| 894 | _audioDeviceModule->InitRecording(); |
| 895 | _audioDeviceModule->StartRecording(); |
| 896 | } |
| 897 | }; |
| 898 | if (id == "default" || id.empty()) { |
| 899 | if (const auto result = _audioDeviceModule->SetRecordingDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 900 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 901 | } else { |
| 902 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) success."; |
| 903 | } |
| 904 | return finish(); |
| 905 | } |
| 906 | const auto count = _audioDeviceModule |
| 907 | ? _audioDeviceModule->RecordingDevices() |
| 908 | : int16_t(-666); |
| 909 | if (count <= 0) { |
| 910 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not get recording devices count: " << count << "."; |
| 911 | return finish(); |
| 912 | } |
| 913 | for (auto i = 0; i != count; ++i) { |
| 914 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 915 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 916 | _audioDeviceModule->RecordingDeviceName(i, name, guid); |
| 917 | if (id == guid) { |
| 918 | const auto result = _audioDeviceModule->SetRecordingDevice(i); |
| 919 | if (result != 0) { |
| 920 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 921 | } else { |
| 922 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 923 | } |
| 924 | return finish(); |
| 925 | } |
| 926 | } |
| 927 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not find recording device."; |
| 928 | return finish(); |
| 929 | } |
| 930 |
| 931 | void MediaManager::setAudioOutputDevice(std::string id) { |
| 932 | const auto playing = _audioDeviceModule->Playing(); |
| 933 | if (playing) { |
| 934 | _audioDeviceModule->StopPlayout(); |
| 935 | } |
| 936 | const auto finish = [&] { |
| 937 | if (playing) { |
| 938 | _audioDeviceModule->InitPlayout(); |
| 939 | _audioDeviceModule->StartPlayout(); |
| 940 | } |
| 941 | }; |
| 942 | if (id == "default" || id.empty()) { |
| 943 | if (const auto result = _audioDeviceModule->SetPlayoutDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 944 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 945 | } else { |
| 946 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) success."; |
| 947 | } |
| 948 | return finish(); |
| 949 | } |
| 950 | const auto count = _audioDeviceModule |
| 951 | ? _audioDeviceModule->PlayoutDevices() |
| 952 | : int16_t(-666); |
| 953 | if (count <= 0) { |
| 954 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not get playout devices count: " << count << "."; |
| 955 | return finish(); |
| 956 | } |
| 957 | for (auto i = 0; i != count; ++i) { |
| 958 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 959 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 960 | _audioDeviceModule->PlayoutDeviceName(i, name, guid); |
| 961 | if (id == guid) { |
| 962 | const auto result = _audioDeviceModule->SetPlayoutDevice(i); |
| 963 | if (result != 0) { |
| 964 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 965 | } else { |
| 966 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 967 | } |
| 968 | return finish(); |
| 969 | } |
| 970 | } |
| 971 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not find playout device."; |
| 972 | return finish(); |
| 973 | } |
| 974 |
| 975 | void MediaManager::setInputVolume(float level) { |
| 976 | // This is not what we want, it changes OS volume on macOS. |
| 977 | // auto min = uint32_t(); |
| 978 | // auto max = uint32_t(); |
| 979 | // if (const auto result = _audioDeviceModule->MinMicrophoneVolume(&min)) { |
| 980 | // RTC_LOG(LS_ERROR) << "setInputVolume(" << level << "): MinMicrophoneVolume failed: " << result << "."; |
| 981 | // return; |
| 982 | // } else if (const auto result = _audioDeviceModule->MaxMicrophoneVolume(&max)) { |
| 983 | // RTC_LOG(LS_ERROR) << "setInputVolume(" << level << "): MaxMicrophoneVolume failed: " << result << "."; |
| 984 | // return; |
| 985 | // } |
| 986 | // const auto volume = min + uint32_t(std::round((max - min) * std::min(std::max(level, 0.f), 1.f))); |
| 987 | // if (const auto result = _audioDeviceModule->SetMicrophoneVolume(volume)) { |
| 988 | // RTC_LOG(LS_ERROR) << "setInputVolume(" << level << "): SetMicrophoneVolume(" << volume << ") failed: " << result << "."; |
| 989 | // } else { |
| 990 | // RTC_LOG(LS_INFO) << "setInputVolume(" << level << ") volume " << volume << " success."; |
| 991 | // } |
| 992 | } |
| 993 |
| 994 | void MediaManager::setOutputVolume(float level) { |
| 995 | // This is not what we want, it changes OS volume on macOS. |
| 996 | // auto min = uint32_t(); |
| 997 | // auto max = uint32_t(); |
| 998 | // if (const auto result = _audioDeviceModule->MinSpeakerVolume(&min)) { |
| 999 | // RTC_LOG(LS_ERROR) << "setOutputVolume(" << level << "): MinSpeakerVolume failed: " << result << "."; |
| 1000 | // return; |
| 1001 | // } else if (const auto result = _audioDeviceModule->MaxSpeakerVolume(&max)) { |
| 1002 | // RTC_LOG(LS_ERROR) << "setOutputVolume(" << level << "): MaxSpeakerVolume failed: " << result << "."; |
| 1003 | // return; |
| 1004 | // } |
| 1005 | // const auto volume = min + uint32_t(std::round((max - min) * std::min(std::max(level, 0.f), 1.f))); |
| 1006 | // if (const auto result = _audioDeviceModule->SetSpeakerVolume(volume)) { |
| 1007 | // RTC_LOG(LS_ERROR) << "setOutputVolume(" << level << "): SetSpeakerVolume(" << volume << ") failed: " << result << "."; |
| 1008 | // } else { |
| 1009 | // RTC_LOG(LS_INFO) << "setOutputVolume(" << level << ") volume " << volume << " success."; |
| 1010 | // } |
| 1011 | } |
| 1012 |
| 1013 | MediaManager::NetworkInterfaceImpl::NetworkInterfaceImpl(MediaManager *mediaManager, bool isVideo) : |
| 1014 | _mediaManager(mediaManager), |
| 1015 | _isVideo(isVideo) { |
| 1016 | } |
| 1017 |
| 1018 | bool MediaManager::NetworkInterfaceImpl::SendPacket(rtc::CopyOnWriteBuffer *packet, const rtc::PacketOptions& options) { |
| 1019 | return sendTransportMessage(packet, options); |
| 1020 | } |
| 1021 |
| 1022 | bool MediaManager::NetworkInterfaceImpl::SendRtcp(rtc::CopyOnWriteBuffer *packet, const rtc::PacketOptions& options) { |
| 1023 | return sendTransportMessage(packet, options); |
| 1024 | } |
| 1025 |
| 1026 | bool MediaManager::NetworkInterfaceImpl::sendTransportMessage(rtc::CopyOnWriteBuffer *packet, const rtc::PacketOptions& options) { |
| 1027 | if (_isVideo) { |
| 1028 | RTC_LOG(LS_VERBOSE) << "Send video packet"; |
| 1029 | } |
| 1030 | _mediaManager->_sendTransportMessage(_isVideo |
| 1031 | ? Message{ VideoDataMessage{ *packet } } |
| 1032 | : Message{ AudioDataMessage{ *packet } }); |
| 1033 | rtc::SentPacket sentPacket(options.packet_id, rtc::TimeMillis(), options.info_signaled_after_sent); |
| 1034 | _mediaManager->notifyPacketSent(sentPacket); |
| 1035 | return true; |
| 1036 | } |
| 1037 |
| 1038 | int MediaManager::NetworkInterfaceImpl::SetOption(cricket::MediaChannel::NetworkInterface::SocketType, rtc::Socket::Option, int) { |
| 1039 | return -1; |
| 1040 | } |
| 1041 |
| 1042 | } // namespace tgcalls |
| 1043 |