MediaManager.cpp 44 KB

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