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