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