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