| 6 | #include "absl/types/optional.h" |
| 7 | #include "rtc_base/thread.h" |
| 8 | #include "rtc_base/time_utils.h" |
| 9 | #include "absl/types/variant.h" |
| 10 | #include "rtc_base/logging.h" |
| 11 | #include "rtc_base/synchronization/mutex.h" |
| 12 | #include "common_audio/ring_buffer.h" |
| 13 | #include "modules/audio_mixer/frame_combiner.h" |
| 14 | #include "modules/audio_processing/agc2/vad_wrapper.h" |
| 15 | #include "modules/audio_processing/audio_buffer.h" |
| 16 | #include "api/video/video_sink_interface.h" |
| 17 | #include "audio/utility/audio_frame_operations.h" |
| 18 |
| 19 | namespace tgcalls { |
| 20 |
| 21 | namespace { |
| 22 |
| 23 | struct PendingAudioSegmentData { |
| 24 | }; |
| 25 |
| 26 | struct PendingUnifiedSegmentData { |
| 27 | }; |
| 28 |
| 29 | struct PendingVideoSegmentData { |
| 30 | int32_t channelId = 0; |
| 31 | VideoChannelDescription::Quality quality = VideoChannelDescription::Quality::Thumbnail; |
| 32 |
| 33 | PendingVideoSegmentData(int32_t channelId_, VideoChannelDescription::Quality quality_) : |
| 34 | channelId(channelId_), |
| 35 | quality(quality_) { |
| 36 | } |
| 37 | }; |
| 38 |
| 39 | struct PendingMediaSegmentPartResult { |
| 40 | std::vector<uint8_t> data; |
| 41 |
| 42 | explicit PendingMediaSegmentPartResult(std::vector<uint8_t> &&data_) : |
| 43 | data(std::move(data_)) { |
| 44 | } |
| 45 | }; |
| 46 |
| 47 | struct PendingMediaSegmentPart { |
| 48 | absl::variant<PendingAudioSegmentData, PendingVideoSegmentData, PendingUnifiedSegmentData> typeData; |
| 49 |
| 50 | int64_t minRequestTimestamp = 0; |
| 51 |
| 52 | std::shared_ptr<BroadcastPartTask> task; |
| 53 | std::shared_ptr<PendingMediaSegmentPartResult> result; |
| 54 | }; |
| 55 |
| 56 | struct PendingMediaSegment { |
| 57 | int64_t timestamp = 0; |
| 58 | std::vector<std::shared_ptr<PendingMediaSegmentPart>> parts; |
| 59 | }; |
| 60 |
| 61 | struct VideoSegment { |
| 62 | VideoChannelDescription::Quality quality; |
| 63 | std::shared_ptr<VideoStreamingPart> part; |
| 64 | double lastFramePts = -1.0; |
| 65 | int _displayedFrames = 0; |
| 66 | bool isPlaying = false; |
| 67 | std::shared_ptr<PendingMediaSegmentPart> pendingVideoQualityUpdatePart; |
| 68 | }; |
| 69 |
| 70 | struct UnifiedSegment { |
| 71 | std::shared_ptr<VideoStreamingPart> videoPart; |
| 72 | double lastFramePts = -1.0; |
| 73 | int _displayedFrames = 0; |
| 74 | bool isPlaying = false; |
| 75 | }; |
| 76 |
| 77 | struct MediaSegment { |
| 78 | int64_t timestamp = 0; |
| 79 | int64_t duration = 0; |
| 80 | std::shared_ptr<AudioStreamingPart> audio; |
| 81 | AudioStreamingPartPersistentDecoder audioDecoder; |
| 82 | std::shared_ptr<VideoStreamingPart> unifiedAudio; |
| 83 | std::vector<std::shared_ptr<VideoSegment>> video; |
| 84 | std::vector<std::shared_ptr<UnifiedSegment>> unified; |
| 85 | }; |
| 86 |
| 87 | class SampleRingBuffer { |
| 88 | public: |
| 89 | SampleRingBuffer(size_t size) { |
| 90 | _buffer = WebRtc_CreateBuffer(size, sizeof(int16_t)); |
| 91 | } |
| 92 |
| 93 | ~SampleRingBuffer() { |
| 94 | if (_buffer) { |
| 95 | WebRtc_FreeBuffer(_buffer); |
| 96 | } |
| 97 | } |
| 98 |
| 99 | size_t availableForWriting() { |
| 100 | return WebRtc_available_write(_buffer); |
| 101 | } |
| 102 |
| 103 | size_t write(int16_t const *samples, size_t count) { |
| 104 | return WebRtc_WriteBuffer(_buffer, samples, count); |
| 105 | } |
| 106 |
| 107 | size_t read(int16_t *samples, size_t count) { |
| 108 | return WebRtc_ReadBuffer(_buffer, nullptr, samples, count); |
| 109 | } |
| 110 |
| 111 | private: |
| 112 | RingBuffer *_buffer = nullptr; |
| 113 | }; |
| 114 |
| 115 | static const int kVadResultHistoryLength = 8; |
| 116 |
| 117 | class VadHistory { |
| 118 | private: |
| 119 | float _vadResultHistory[kVadResultHistoryLength]; |
| 120 |
| 121 | public: |
| 122 | VadHistory() { |
| 123 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 124 | _vadResultHistory[i] = 0.0f; |
| 125 | } |
| 126 | } |
| 127 |
| 128 | ~VadHistory() { |
| 129 | } |
| 130 |
| 131 | bool update(float vadProbability) { |
| 132 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 133 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 134 | } |
| 135 | _vadResultHistory[kVadResultHistoryLength - 1] = vadProbability; |
| 136 |
| 137 | float movingAverage = 0.0f; |
| 138 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 139 | movingAverage += _vadResultHistory[i]; |
| 140 | } |
| 141 | movingAverage /= (float)kVadResultHistoryLength; |
| 142 |
| 143 | bool vadResult = false; |
| 144 | if (movingAverage > 0.8f) { |
| 145 | vadResult = true; |
| 146 | } |
| 147 |
| 148 | return vadResult; |
| 149 | } |
| 150 | }; |
| 151 |
| 152 | class CombinedVad { |
| 153 | private: |
| 154 | webrtc::VoiceActivityDetectorWrapper _vadWithLevel; |
| 155 | VadHistory _history; |
| 156 |
| 157 | public: |
| 158 | CombinedVad() : |
| 159 | _vadWithLevel(500, webrtc::GetAvailableCpuFeatures(), webrtc::AudioProcessing::kSampleRate48kHz) { |
| 160 | } |
| 161 |
| 162 | ~CombinedVad() { |
| 163 | } |
| 164 |
| 165 | bool update(webrtc::AudioBuffer *buffer) { |
| 166 | if (buffer->num_channels() <= 0) { |
| 167 | return _history.update(0.0f); |
| 168 | } |
| 169 | webrtc::AudioFrameView<float> frameView(buffer->channels(), (int)(buffer->num_channels()), (int)(buffer->num_frames())); |
| 170 | float peak = 0.0f; |
| 171 | for (const auto &x : frameView.channel(0)) { |
| 172 | peak = std::max(std::fabs(x), peak); |
| 173 | } |
| 174 | if (peak <= 0.01f) { |
| 175 | return _history.update(false); |
| 176 | } |
| 177 |
| 178 | auto result = _vadWithLevel.Analyze(frameView); |
| 179 |
| 180 | return _history.update(result); |
| 181 | } |
| 182 |
| 183 | bool update() { |
| 184 | return _history.update(0.0f); |
| 185 | } |
| 186 | }; |
| 187 |
| 188 | class SparseVad { |
| 189 | public: |
| 190 | SparseVad() { |
| 191 | } |
| 192 |
| 193 | std::pair<float, bool> update(webrtc::AudioBuffer *buffer) { |
| 194 | _sampleCount += buffer->num_frames(); |
| 195 | if (_sampleCount >= 400) { |
| 196 | _sampleCount = 0; |
| 197 | _currentValue = _vad.update(buffer); |
| 198 | } |
| 199 |
| 200 | float currentPeak = 0.0; |
| 201 | float *samples = buffer->channels()[0]; |
| 202 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 203 | float sample = samples[i]; |
| 204 | if (sample < 0.0f) { |
| 205 | sample = -sample; |
| 206 | } |
| 207 | if (_peak < sample) { |
| 208 | _peak = sample; |
| 209 | } |
| 210 | if (currentPeak < sample) { |
| 211 | currentPeak = sample; |
| 212 | } |
| 213 | _peakCount += 1; |
| 214 | } |
| 215 |
| 216 | if (_peakCount >= 4400) { |
| 217 | float norm = 8000.0f; |
| 218 | _currentLevel = ((float)(_peak)) / norm; |
| 219 | _peak = 0; |
| 220 | _peakCount = 0; |
| 221 | } |
| 222 |
| 223 | return std::make_pair(_currentLevel, _currentValue); |
| 224 | } |
| 225 |
| 226 | private: |
| 227 | CombinedVad _vad; |
| 228 | bool _currentValue = false; |
| 229 | size_t _sampleCount = 0; |
| 230 |
| 231 | int _peakCount = 0; |
| 232 | float _peak = 0.0; |
| 233 | float _currentLevel = 0.0; |
| 234 | }; |
| 235 |
| 236 | } |
| 237 |
| 238 | class StreamingMediaContextPrivate : public std::enable_shared_from_this<StreamingMediaContextPrivate> { |
| 239 | public: |
| 240 | StreamingMediaContextPrivate(StreamingMediaContext::StreamingMediaContextArguments &&arguments) : |
| 241 | _threads(arguments.threads), |
| 242 | _isUnifiedBroadcast(arguments.isUnifiedBroadcast), |
| 243 | _requestCurrentTime(arguments.requestCurrentTime), |
| 244 | _requestAudioBroadcastPart(arguments.requestAudioBroadcastPart), |
| 245 | _requestVideoBroadcastPart(arguments.requestVideoBroadcastPart), |
| 246 | _updateAudioLevel(arguments.updateAudioLevel), |
| 247 | _audioRingBuffer(_audioDataRingBufferMaxSize), |
| 248 | _audioFrameCombiner(false), |
| 249 | _platformContext(arguments.platformContext) { |
| 250 | } |
| 251 |
| 252 | ~StreamingMediaContextPrivate() { |
| 253 | } |
| 254 |
| 255 | void start() { |
| 256 | beginRenderTimer(0); |
| 257 | } |
| 258 |
| 259 | void beginRenderTimer(int timeoutMs) { |
| 260 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 261 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 262 | auto strong = weak.lock(); |
| 263 | if (!strong) { |
| 264 | return; |
| 265 | } |
| 266 |
| 267 | strong->render(); |
| 268 |
| 269 | strong->beginRenderTimer((int)(1.0 * 1000.0 / 120.0)); |
| 270 | }, webrtc::TimeDelta::Millis(timeoutMs)); |
| 271 | } |
| 272 |
| 273 | void render() { |
| 274 | int64_t absoluteTimestamp = rtc::TimeMillis(); |
| 275 |
| 276 | while (true) { |
| 277 | if (_waitForBufferredMillisecondsBeforeRendering) { |
| 278 | if (getAvailableBufferDuration() < _waitForBufferredMillisecondsBeforeRendering.value()) { |
| 279 | break; |
| 280 | } else { |
| 281 | _waitForBufferredMillisecondsBeforeRendering = absl::nullopt; |
| 282 | } |
| 283 | } |
| 284 |
| 285 | if (_availableSegments.empty()) { |
| 286 | _playbackReferenceTimestamp = 0; |
| 287 |
| 288 | _waitForBufferredMillisecondsBeforeRendering = _segmentBufferDuration + _segmentDuration; |
| 289 |
| 290 | break; |
| 291 | } |
| 292 |
| 293 | if (_playbackReferenceTimestamp == 0) { |
| 294 | _playbackReferenceTimestamp = absoluteTimestamp; |
| 295 | } |
| 296 |
| 297 | double relativeTimestamp = ((double)(absoluteTimestamp - _playbackReferenceTimestamp)) / 1000.0; |
| 298 |
| 299 | auto segment = _availableSegments[0]; |
| 300 | double segmentDuration = ((double)segment->duration) / 1000.0; |
| 301 |
| 302 | for (auto &videoSegment : segment->video) { |
| 303 | videoSegment->isPlaying = true; |
| 304 | cancelPendingVideoQualityUpdate(videoSegment); |
| 305 |
| 306 | std::shared_ptr<VideoStreamingSharedState> sharedVideoState; |
| 307 | auto endpointId = videoSegment->part->getActiveEndpointId(); |
| 308 | if (endpointId.has_value()) { |
| 309 | auto it = _sharedVideoStateByEndpointId.find(endpointId.value()); |
| 310 | if (it != _sharedVideoStateByEndpointId.end()) { |
| 311 | sharedVideoState = it->second; |
| 312 | } else { |
| 313 | sharedVideoState = std::make_shared<VideoStreamingSharedState>(); |
| 314 | _sharedVideoStateByEndpointId.insert(std::make_pair(endpointId.value(), sharedVideoState)); |
| 315 | } |
| 316 | } |
| 317 |
| 318 | auto frame = videoSegment->part->getFrameAtRelativeTimestamp(sharedVideoState.get(), relativeTimestamp); |
| 319 | if (frame) { |
| 320 | if (videoSegment->lastFramePts != frame->pts) { |
| 321 | videoSegment->lastFramePts = frame->pts; |
| 322 | videoSegment->_displayedFrames += 1; |
| 323 |
| 324 | auto sinkList = _videoSinks.find(frame->endpointId); |
| 325 | if (sinkList != _videoSinks.end()) { |
| 326 | for (const auto &weakSink : sinkList->second) { |
| 327 | auto sink = weakSink.lock(); |
| 328 | if (sink) { |
| 329 | sink->OnFrame(frame->frame); |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 |
| 337 | for (auto &videoSegment : segment->unified) { |
| 338 | videoSegment->isPlaying = true; |
| 339 |
| 340 | absl::optional<std::string> endpointId = "unified"; |
| 341 | std::shared_ptr<VideoStreamingSharedState> sharedVideoState; |
| 342 | if (endpointId.has_value()) { |
| 343 | auto it = _sharedVideoStateByEndpointId.find(endpointId.value()); |
| 344 | if (it != _sharedVideoStateByEndpointId.end()) { |
| 345 | sharedVideoState = it->second; |
| 346 | } else { |
| 347 | sharedVideoState = std::make_shared<VideoStreamingSharedState>(); |
| 348 | _sharedVideoStateByEndpointId.insert(std::make_pair(endpointId.value(), sharedVideoState)); |
| 349 | } |
| 350 | } |
| 351 |
| 352 | auto frame = videoSegment->videoPart->getFrameAtRelativeTimestamp(sharedVideoState.get(), relativeTimestamp); |
| 353 | if (frame) { |
| 354 | if (videoSegment->lastFramePts != frame->pts) { |
| 355 | videoSegment->lastFramePts = frame->pts; |
| 356 | videoSegment->_displayedFrames += 1; |
| 357 |
| 358 | auto sinkList = _videoSinks.find("unified"); |
| 359 | if (sinkList != _videoSinks.end()) { |
| 360 | for (const auto &weakSink : sinkList->second) { |
| 361 | auto sink = weakSink.lock(); |
| 362 | if (sink) { |
| 363 | sink->OnFrame(frame->frame); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 |
| 371 | if (segment->audio) { |
| 372 | const auto available = [&] { |
| 373 | _audioDataMutex.Lock(); |
| 374 | const auto result = (_audioRingBuffer.availableForWriting() >= 480 * _audioRingBufferNumChannels); |
| 375 | _audioDataMutex.Unlock(); |
| 376 |
| 377 | return result; |
| 378 | }; |
| 379 | while (available()) { |
| 380 | auto audioChannels = segment->audio->get10msPerChannel(segment->audioDecoder); |
| 381 | if (audioChannels.empty()) { |
| 382 | break; |
| 383 | } |
| 384 |
| 385 | std::vector<webrtc::AudioFrame *> audioFrames; |
| 386 |
| 387 | for (const auto &audioChannel : audioChannels) { |
| 388 | webrtc::AudioFrame *frame = new webrtc::AudioFrame(); |
| 389 | frame->UpdateFrame(0, audioChannel.pcmData.data(), audioChannel.pcmData.size(), 48000, webrtc::AudioFrame::SpeechType::kNormalSpeech, webrtc::AudioFrame::VADActivity::kVadActive); |
| 390 |
| 391 | auto volumeIt = _volumeBySsrc.find(audioChannel.ssrc); |
| 392 | if (volumeIt != _volumeBySsrc.end()) { |
| 393 | double outputGain = volumeIt->second; |
| 394 | if (outputGain < 0.99f || outputGain > 1.01f) { |
| 395 | webrtc::AudioFrameOperations::ScaleWithSat(outputGain, frame); |
| 396 | } |
| 397 | } |
| 398 |
| 399 | audioFrames.push_back(frame); |
| 400 | processAudioLevel(audioChannel.ssrc, audioChannel.pcmData); |
| 401 | } |
| 402 |
| 403 | webrtc::AudioFrame frameOut; |
| 404 | _audioFrameCombiner.Combine(audioFrames, 1, 48000, audioFrames.size(), &frameOut); |
| 405 |
| 406 | for (webrtc::AudioFrame *frame : audioFrames) { |
| 407 | delete frame; |
| 408 | } |
| 409 |
| 410 | _audioDataMutex.Lock(); |
| 411 | if (frameOut.num_channels() == _audioRingBufferNumChannels) { |
| 412 | _audioRingBuffer.write(frameOut.data(), frameOut.samples_per_channel() * frameOut.num_channels()); |
| 413 | } else { |
| 414 | if (_stereoShuffleBuffer.size() < frameOut.samples_per_channel() * _audioRingBufferNumChannels) { |
| 415 | _stereoShuffleBuffer.resize(frameOut.samples_per_channel() * _audioRingBufferNumChannels); |
| 416 | } |
| 417 | for (int i = 0; i < frameOut.samples_per_channel(); i++) { |
| 418 | for (int j = 0; j < _audioRingBufferNumChannels; j++) { |
| 419 | _stereoShuffleBuffer[i * _audioRingBufferNumChannels + j] = frameOut.data()[i]; |
| 420 | } |
| 421 | } |
| 422 | _audioRingBuffer.write(_stereoShuffleBuffer.data(), frameOut.samples_per_channel() * _audioRingBufferNumChannels); |
| 423 | } |
| 424 | _audioDataMutex.Unlock(); |
| 425 | } |
| 426 | } else if (segment->unifiedAudio) { |
| 427 | const auto available = [&] { |
| 428 | _audioDataMutex.Lock(); |
| 429 | const auto result = (_audioRingBuffer.availableForWriting() >= 480 * _audioRingBufferNumChannels); |
| 430 | _audioDataMutex.Unlock(); |
| 431 |
| 432 | return result; |
| 433 | }; |
| 434 | while (available()) { |
| 435 | auto audioChannels = segment->unifiedAudio->getAudio10msPerChannel(_persistentAudioDecoder); |
| 436 | if (audioChannels.empty()) { |
| 437 | break; |
| 438 | } |
| 439 |
| 440 | if (audioChannels[0].numSamples < 480) { |
| 441 | RTC_LOG(LS_INFO) << "render: got less than 10ms of audio data (" << audioChannels[0].numSamples << " samples)"; |
| 442 | } |
| 443 |
| 444 | int numChannels = std::min(2, (int)audioChannels.size()); |
| 445 |
| 446 | webrtc::AudioFrame frameOut; |
| 447 |
| 448 | if (numChannels == 1) { |
| 449 | frameOut.UpdateFrame(0, audioChannels[0].pcmData.data(), audioChannels[0].pcmData.size(), 48000, webrtc::AudioFrame::SpeechType::kNormalSpeech, webrtc::AudioFrame::VADActivity::kVadActive, numChannels); |
| 450 | } else if (numChannels == _audioRingBufferNumChannels) { |
| 451 | bool skipFrame = false; |
| 452 | int numSamples = (int)audioChannels[0].pcmData.size(); |
| 453 | for (int i = 1; i < numChannels; i++) { |
| 454 | if (audioChannels[i].pcmData.size() != numSamples) { |
| 455 | skipFrame = true; |
| 456 | break; |
| 457 | } |
| 458 | } |
| 459 | if (skipFrame) { |
| 460 | break; |
| 461 | } |
| 462 | if (_stereoShuffleBuffer.size() < numChannels * numSamples) { |
| 463 | _stereoShuffleBuffer.resize(numChannels * numSamples); |
| 464 | } |
| 465 | for (int i = 0; i < numSamples; i++) { |
| 466 | for (int j = 0; j < numChannels; j++) { |
| 467 | _stereoShuffleBuffer[i * numChannels + j] = audioChannels[j].pcmData[i]; |
| 468 | } |
| 469 | } |
| 470 | frameOut.UpdateFrame(0, _stereoShuffleBuffer.data(), numSamples, 48000, webrtc::AudioFrame::SpeechType::kNormalSpeech, webrtc::AudioFrame::VADActivity::kVadActive, numChannels); |
| 471 | } else { |
| 472 | bool skipFrame = false; |
| 473 | int numSamples = (int)audioChannels[0].pcmData.size(); |
| 474 | for (int i = 1; i < numChannels; i++) { |
| 475 | if (audioChannels[i].pcmData.size() != numSamples) { |
| 476 | skipFrame = true; |
| 477 | break; |
| 478 | } |
| 479 | } |
| 480 | if (skipFrame) { |
| 481 | break; |
| 482 | } |
| 483 | if (_stereoShuffleBuffer.size() < numChannels * numSamples) { |
| 484 | _stereoShuffleBuffer.resize(numChannels * numSamples); |
| 485 | } |
| 486 | for (int i = 0; i < numSamples; i++) { |
| 487 | for (int j = 0; j < numChannels; j++) { |
| 488 | _stereoShuffleBuffer[i * numChannels + j] = audioChannels[0].pcmData[i]; |
| 489 | } |
| 490 | } |
| 491 | frameOut.UpdateFrame(0, _stereoShuffleBuffer.data(), numSamples, 48000, webrtc::AudioFrame::SpeechType::kNormalSpeech, webrtc::AudioFrame::VADActivity::kVadActive, numChannels); |
| 492 | } |
| 493 |
| 494 | auto volumeIt = _volumeBySsrc.find(1); |
| 495 | if (volumeIt != _volumeBySsrc.end()) { |
| 496 | double outputGain = volumeIt->second; |
| 497 | if (outputGain < 0.99f || outputGain > 1.01f) { |
| 498 | webrtc::AudioFrameOperations::ScaleWithSat(outputGain, &frameOut); |
| 499 | } |
| 500 | } |
| 501 |
| 502 | _audioDataMutex.Lock(); |
| 503 | if (frameOut.num_channels() == _audioRingBufferNumChannels) { |
| 504 | _audioRingBuffer.write(frameOut.data(), frameOut.samples_per_channel() * frameOut.num_channels()); |
| 505 | } else { |
| 506 | if (_stereoShuffleBuffer.size() < frameOut.samples_per_channel() * _audioRingBufferNumChannels) { |
| 507 | _stereoShuffleBuffer.resize(frameOut.samples_per_channel() * _audioRingBufferNumChannels); |
| 508 | } |
| 509 | for (int i = 0; i < frameOut.samples_per_channel(); i++) { |
| 510 | for (int j = 0; j < _audioRingBufferNumChannels; j++) { |
| 511 | _stereoShuffleBuffer[i * _audioRingBufferNumChannels + j] = frameOut.data()[i]; |
| 512 | } |
| 513 | } |
| 514 | _audioRingBuffer.write(_stereoShuffleBuffer.data(), frameOut.samples_per_channel() * _audioRingBufferNumChannels); |
| 515 | } |
| 516 | _audioDataMutex.Unlock(); |
| 517 | } |
| 518 | } |
| 519 |
| 520 | if (relativeTimestamp >= segmentDuration) { |
| 521 | _playbackReferenceTimestamp += segment->duration; |
| 522 |
| 523 | if (segment->audio && segment->audio->getRemainingMilliseconds() > 0) { |
| 524 | RTC_LOG(LS_INFO) << "render: discarding " << segment->audio->getRemainingMilliseconds() << " ms of audio at the end of a segment"; |
| 525 | } |
| 526 | if (!segment->video.empty()) { |
| 527 | if (segment->video[0]->part->getActiveEndpointId()) { |
| 528 | RTC_LOG(LS_INFO) << "render: discarding video frames at the end of a segment (displayed " << segment->video[0]->_displayedFrames << " frames)"; |
| 529 | } |
| 530 | } |
| 531 | if (!segment->unified.empty() && segment->unified[0]->videoPart->hasRemainingFrames()) { |
| 532 | RTC_LOG(LS_INFO) << "render: discarding video frames at the end of a segment (displayed " << segment->unified[0]->_displayedFrames << " frames)"; |
| 533 | } |
| 534 |
| 535 | _availableSegments.erase(_availableSegments.begin()); |
| 536 | } else if ( |
| 537 | _availableSegments.size() > 1 && |
| 538 | (!segment->audio || segment->audio->getRemainingMilliseconds() <= 0) && |
| 539 | (segment->video.empty() || !segment->video[0]->part->getActiveEndpointId()) && |
| 540 | (segment->unified.empty() || !segment->unified[0]->videoPart->hasRemainingFrames()) && |
| 541 | (!segment->unifiedAudio || !segment->unifiedAudio->hasRemainingFrames()) |
| 542 | ) { |
| 543 | _playbackReferenceTimestamp += segment->duration; |
| 544 | _waitForBufferredMillisecondsBeforeRendering = absl::nullopt; |
| 545 |
| 546 | _availableSegments.erase(_availableSegments.begin()); |
| 547 | } |
| 548 |
| 549 | break; |
| 550 | } |
| 551 |
| 552 | requestSegmentsIfNeeded(); |
| 553 | checkPendingSegments(); |
| 554 | } |
| 555 |
| 556 | void processAudioLevel(uint32_t ssrc, std::vector<int16_t> const &samples) { |
| 557 | if (!_updateAudioLevel) { |
| 558 | return; |
| 559 | } |
| 560 |
| 561 | webrtc::AudioBuffer buffer(48000, 1, 48000, 1, 48000, 1); |
| 562 | webrtc::StreamConfig config(48000, 1); |
| 563 | buffer.CopyFrom(samples.data(), config); |
| 564 |
| 565 | std::pair<float, bool> vadResult = std::make_pair(0.0f, false); |
| 566 | auto vad = _audioVadMap.find(ssrc); |
| 567 | if (vad == _audioVadMap.end()) { |
| 568 | auto newVad = std::make_unique<SparseVad>(); |
| 569 | vadResult = newVad->update(&buffer); |
| 570 | _audioVadMap.insert(std::make_pair(ssrc, std::move(newVad))); |
| 571 | } else { |
| 572 | vadResult = vad->second->update(&buffer); |
| 573 | } |
| 574 |
| 575 | _updateAudioLevel(ssrc, vadResult.first, vadResult.second); |
| 576 | } |
| 577 |
| 578 | void getAudio(int16_t *audio_samples, size_t num_samples, size_t num_channels, uint32_t samples_per_sec) { |
| 579 | int16_t *buffer = nullptr; |
| 580 |
| 581 | if (num_channels == _audioRingBufferNumChannels) { |
| 582 | buffer = audio_samples; |
| 583 | } else { |
| 584 | if (_tempAudioBuffer.size() < num_samples * _audioRingBufferNumChannels) { |
| 585 | _tempAudioBuffer.resize(num_samples * _audioRingBufferNumChannels); |
| 586 | } |
| 587 | buffer = _tempAudioBuffer.data(); |
| 588 | } |
| 589 |
| 590 | _audioDataMutex.Lock(); |
| 591 | size_t readSamples = _audioRingBuffer.read(buffer, num_samples * _audioRingBufferNumChannels); |
| 592 | _audioDataMutex.Unlock(); |
| 593 |
| 594 | if (num_channels != _audioRingBufferNumChannels) { |
| 595 | for (size_t sampleIndex = 0; sampleIndex < readSamples / _audioRingBufferNumChannels; sampleIndex++) { |
| 596 | for (size_t channelIndex = 0; channelIndex < num_channels; channelIndex++) { |
| 597 | audio_samples[sampleIndex * num_channels + channelIndex] = _tempAudioBuffer[sampleIndex * _audioRingBufferNumChannels + 0]; |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | if (readSamples < num_samples * num_channels) { |
| 602 | memset(audio_samples + readSamples, 0, (num_samples * num_channels - readSamples) * sizeof(int16_t)); |
| 603 | } |
| 604 | } |
| 605 |
| 606 | int64_t getAvailableBufferDuration() { |
| 607 | int64_t result = 0; |
| 608 |
| 609 | for (const auto &segment : _availableSegments) { |
| 610 | result += segment->duration; |
| 611 | } |
| 612 |
| 613 | return (int)result; |
| 614 | } |
| 615 |
| 616 | void discardAllPendingSegments() { |
| 617 | for (size_t i = 0; i < _pendingSegments.size(); i++) { |
| 618 | for (const auto &it : _pendingSegments[i]->parts) { |
| 619 | if (it->task) { |
| 620 | it->task->cancel(); |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 |
| 625 | _pendingSegments.clear(); |
| 626 | } |
| 627 |
| 628 | void requestSegmentsIfNeeded() { |
| 629 | while (true) { |
| 630 | if (_nextSegmentTimestamp == -1) { |
| 631 | if (!_pendingRequestTimeTask && _pendingRequestTimeDelayTaskId == 0) { |
| 632 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 633 | _pendingRequestTimeTask = _requestCurrentTime([weak, threads = _threads](int64_t timestamp) { |
| 634 | threads->getMediaThread()->PostTask([weak, timestamp]() { |
| 635 | auto strong = weak.lock(); |
| 636 | if (!strong) { |
| 637 | return; |
| 638 | } |
| 639 |
| 640 | strong->_pendingRequestTimeTask.reset(); |
| 641 |
| 642 | int64_t adjustedTimestamp = 0; |
| 643 | if (timestamp > 0) { |
| 644 | adjustedTimestamp = (int64_t)((timestamp / strong->_segmentDuration * strong->_segmentDuration) - strong->_segmentBufferDuration); |
| 645 | } |
| 646 |
| 647 | if (adjustedTimestamp <= 0) { |
| 648 | int taskId = strong->_nextPendingRequestTimeDelayTaskId; |
| 649 | strong->_pendingRequestTimeDelayTaskId = taskId; |
| 650 | strong->_nextPendingRequestTimeDelayTaskId++; |
| 651 |
| 652 | strong->_threads->getMediaThread()->PostDelayedTask([weak, taskId]() { |
| 653 | auto strong = weak.lock(); |
| 654 | if (!strong) { |
| 655 | return; |
| 656 | } |
| 657 | if (strong->_pendingRequestTimeDelayTaskId != taskId) { |
| 658 | return; |
| 659 | } |
| 660 |
| 661 | strong->_pendingRequestTimeDelayTaskId = 0; |
| 662 |
| 663 | strong->requestSegmentsIfNeeded(); |
| 664 | }, webrtc::TimeDelta::Millis(1000)); |
| 665 | } else { |
| 666 | strong->_nextSegmentTimestamp = adjustedTimestamp; |
| 667 | strong->requestSegmentsIfNeeded(); |
| 668 | } |
| 669 | }); |
| 670 | }); |
| 671 | } |
| 672 | break; |
| 673 | } else { |
| 674 | int64_t availableAndRequestedSegmentsDuration = 0; |
| 675 | availableAndRequestedSegmentsDuration += getAvailableBufferDuration(); |
| 676 | availableAndRequestedSegmentsDuration += _pendingSegments.size() * _segmentDuration; |
| 677 |
| 678 | if (availableAndRequestedSegmentsDuration > _segmentBufferDuration) { |
| 679 | break; |
| 680 | } |
| 681 | } |
| 682 |
| 683 | auto pendingSegment = std::make_shared<PendingMediaSegment>(); |
| 684 | pendingSegment->timestamp = _nextSegmentTimestamp; |
| 685 |
| 686 | if (_nextSegmentTimestamp != -1) { |
| 687 | _nextSegmentTimestamp += _segmentDuration; |
| 688 | } |
| 689 |
| 690 | auto audio = std::make_shared<PendingMediaSegmentPart>(); |
| 691 | if (_isUnifiedBroadcast) { |
| 692 | audio->typeData = PendingUnifiedSegmentData(); |
| 693 | } else { |
| 694 | audio->typeData = PendingAudioSegmentData(); |
| 695 | } |
| 696 | audio->minRequestTimestamp = 0; |
| 697 | pendingSegment->parts.push_back(audio); |
| 698 |
| 699 | for (const auto &videoChannel : _activeVideoChannels) { |
| 700 | auto channelIdIt = _currentEndpointMapping.find(videoChannel.endpoint); |
| 701 | if (channelIdIt == _currentEndpointMapping.end()) { |
| 702 | continue; |
| 703 | } |
| 704 |
| 705 | int32_t channelId = channelIdIt->second + 1; |
| 706 |
| 707 | auto video = std::make_shared<PendingMediaSegmentPart>(); |
| 708 | video->typeData = PendingVideoSegmentData(channelId, videoChannel.quality); |
| 709 | video->minRequestTimestamp = 0; |
| 710 | pendingSegment->parts.push_back(video); |
| 711 | } |
| 712 |
| 713 | _pendingSegments.push_back(pendingSegment); |
| 714 |
| 715 | if (_nextSegmentTimestamp == -1) { |
| 716 | break; |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 |
| 721 | void requestPendingVideoQualityUpdate(std::shared_ptr<VideoSegment> segment, int64_t timestamp) { |
| 722 | if (segment->isPlaying) { |
| 723 | return; |
| 724 | } |
| 725 | auto segmentEndpointId = segment->part->getActiveEndpointId(); |
| 726 | if (!segmentEndpointId) { |
| 727 | return; |
| 728 | } |
| 729 |
| 730 | absl::optional<int32_t> updatedChannelId; |
| 731 | absl::optional<VideoChannelDescription::Quality> updatedQuality; |
| 732 |
| 733 | for (const auto &videoChannel : _activeVideoChannels) { |
| 734 | auto channelIdIt = _currentEndpointMapping.find(videoChannel.endpoint); |
| 735 | if (channelIdIt == _currentEndpointMapping.end()) { |
| 736 | continue; |
| 737 | } |
| 738 |
| 739 | updatedChannelId = channelIdIt->second + 1; |
| 740 | updatedQuality = videoChannel.quality; |
| 741 | } |
| 742 |
| 743 | if (updatedChannelId && updatedQuality) { |
| 744 | if (segment->pendingVideoQualityUpdatePart) { |
| 745 | const auto typeData = &segment->pendingVideoQualityUpdatePart->typeData; |
| 746 | if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 747 | if (videoData->channelId == updatedChannelId.value() && videoData->quality == updatedQuality.value()) { |
| 748 | return; |
| 749 | } |
| 750 | } |
| 751 | cancelPendingVideoQualityUpdate(segment); |
| 752 | } |
| 753 |
| 754 | auto video = std::make_shared<PendingMediaSegmentPart>(); |
| 755 |
| 756 | video->typeData = PendingVideoSegmentData(updatedChannelId.value(), updatedQuality.value()); |
| 757 | video->minRequestTimestamp = 0; |
| 758 |
| 759 | segment->pendingVideoQualityUpdatePart = video; |
| 760 |
| 761 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 762 | const auto weakSegment = std::weak_ptr<VideoSegment>(segment); |
| 763 | beginPartTask(video, timestamp, [weak, weakSegment]() { |
| 764 | auto strong = weak.lock(); |
| 765 | if (!strong) { |
| 766 | return; |
| 767 | } |
| 768 |
| 769 | auto strongSegment = weakSegment.lock(); |
| 770 | if (!strongSegment) { |
| 771 | return; |
| 772 | } |
| 773 |
| 774 | if (!strongSegment->pendingVideoQualityUpdatePart) { |
| 775 | return; |
| 776 | } |
| 777 |
| 778 | auto result = strongSegment->pendingVideoQualityUpdatePart->result; |
| 779 | if (result) { |
| 780 | strongSegment->part = std::make_shared<VideoStreamingPart>(std::move(result->data), VideoStreamingPart::ContentType::Video); |
| 781 | } |
| 782 |
| 783 | strongSegment->pendingVideoQualityUpdatePart.reset(); |
| 784 | }); |
| 785 | } |
| 786 | } |
| 787 |
| 788 | void cancelPendingVideoQualityUpdate(std::shared_ptr<VideoSegment> segment) { |
| 789 | if (!segment->pendingVideoQualityUpdatePart) { |
| 790 | return; |
| 791 | } |
| 792 |
| 793 | if (segment->pendingVideoQualityUpdatePart->task) { |
| 794 | segment->pendingVideoQualityUpdatePart->task->cancel(); |
| 795 | } |
| 796 |
| 797 | segment->pendingVideoQualityUpdatePart.reset(); |
| 798 | } |
| 799 |
| 800 | void checkPendingSegments() { |
| 801 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 802 |
| 803 | int64_t absoluteTimestamp = rtc::TimeMillis(); |
| 804 | int64_t minDelayedRequestTimeout = INT_MAX; |
| 805 |
| 806 | bool shouldRequestMoreSegments = false; |
| 807 |
| 808 | for (int i = 0; i < _pendingSegments.size(); i++) { |
| 809 | auto pendingSegment = _pendingSegments[i]; |
| 810 | auto segmentTimestamp = pendingSegment->timestamp; |
| 811 |
| 812 | bool allPartsDone = true; |
| 813 |
| 814 | for (auto &part : pendingSegment->parts) { |
| 815 | if (!part->result) { |
| 816 | allPartsDone = false; |
| 817 | } |
| 818 |
| 819 | if (!part->result && !part->task) { |
| 820 | if (part->minRequestTimestamp != 0) { |
| 821 | if (part->minRequestTimestamp > absoluteTimestamp) { |
| 822 | minDelayedRequestTimeout = std::min(minDelayedRequestTimeout, part->minRequestTimestamp - absoluteTimestamp); |
| 823 |
| 824 | continue; |
| 825 | } |
| 826 | } |
| 827 |
| 828 | const auto weakSegment = std::weak_ptr<PendingMediaSegment>(pendingSegment); |
| 829 | const auto weakPart = std::weak_ptr<PendingMediaSegmentPart>(part); |
| 830 |
| 831 | std::function<void(BroadcastPart &&)> handleResult = [weak, weakSegment, weakPart, threads = _threads, segmentTimestamp](BroadcastPart &&part) { |
| 832 | threads->getMediaThread()->PostTask([weak, weakSegment, weakPart, part = std::move(part), segmentTimestamp]() mutable { |
| 833 | auto strong = weak.lock(); |
| 834 | if (!strong) { |
| 835 | return; |
| 836 | } |
| 837 | auto strongSegment = weakSegment.lock(); |
| 838 | if (!strongSegment) { |
| 839 | return; |
| 840 | } |
| 841 |
| 842 | auto pendingPart = weakPart.lock(); |
| 843 | if (!pendingPart) { |
| 844 | return; |
| 845 | } |
| 846 |
| 847 | pendingPart->task.reset(); |
| 848 |
| 849 | switch (part.status) { |
| 850 | case BroadcastPart::Status::Success: { |
| 851 | pendingPart->result = std::make_shared<PendingMediaSegmentPartResult>(std::move(part.data)); |
| 852 | if (strong->_nextSegmentTimestamp == -1) { |
| 853 | strong->_nextSegmentTimestamp = part.timestampMilliseconds + strong->_segmentDuration; |
| 854 | } |
| 855 | strong->checkPendingSegments(); |
| 856 | break; |
| 857 | } |
| 858 | case BroadcastPart::Status::NotReady: { |
| 859 | if (segmentTimestamp == 0 && !strong->_isUnifiedBroadcast) { |
| 860 | int64_t responseTimestampMilliseconds = (int64_t)(part.responseTimestamp * 1000.0); |
| 861 | int64_t responseTimestampBoundary = (responseTimestampMilliseconds / strong->_segmentDuration) * strong->_segmentDuration; |
| 862 |
| 863 | strong->_nextSegmentTimestamp = responseTimestampBoundary; |
| 864 | strong->discardAllPendingSegments(); |
| 865 | strong->requestSegmentsIfNeeded(); |
| 866 | strong->checkPendingSegments(); |
| 867 | } else { |
| 868 | pendingPart->minRequestTimestamp = rtc::TimeMillis() + 100; |
| 869 | strong->checkPendingSegments(); |
| 870 | } |
| 871 | break; |
| 872 | } |
| 873 | case BroadcastPart::Status::ResyncNeeded: { |
| 874 | if (strong->_isUnifiedBroadcast) { |
| 875 | strong->_nextSegmentTimestamp = -1; |
| 876 | } else { |
| 877 | int64_t responseTimestampMilliseconds = (int64_t)(part.responseTimestamp * 1000.0); |
| 878 | int64_t responseTimestampBoundary = (responseTimestampMilliseconds / strong->_segmentDuration) * strong->_segmentDuration; |
| 879 |
| 880 | strong->_nextSegmentTimestamp = responseTimestampBoundary; |
| 881 | } |
| 882 |
| 883 | strong->discardAllPendingSegments(); |
| 884 | strong->requestSegmentsIfNeeded(); |
| 885 | strong->checkPendingSegments(); |
| 886 |
| 887 | break; |
| 888 | } |
| 889 | default: { |
| 890 | RTC_FATAL() << "Unknown part.status"; |
| 891 | break; |
| 892 | } |
| 893 | } |
| 894 | }); |
| 895 | }; |
| 896 |
| 897 | const auto typeData = &part->typeData; |
| 898 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 899 | part->task = _requestAudioBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, handleResult); |
| 900 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 901 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, videoData->channelId, videoData->quality, handleResult); |
| 902 | } else if (const auto unifiedData = absl::get_if<PendingUnifiedSegmentData>(typeData)) { |
| 903 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, 1, VideoChannelDescription::Quality::Full, handleResult); |
| 904 | } |
| 905 | } |
| 906 | } |
| 907 |
| 908 | if (allPartsDone && i == 0) { |
| 909 | std::shared_ptr<MediaSegment> segment = std::make_shared<MediaSegment>(); |
| 910 | segment->timestamp = pendingSegment->timestamp; |
| 911 | segment->duration = _segmentDuration; |
| 912 | for (auto &part : pendingSegment->parts) { |
| 913 | const auto typeData = &part->typeData; |
| 914 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 915 | segment->audio = std::make_shared<AudioStreamingPart>(std::move(part->result->data), "ogg", false); |
| 916 | _currentEndpointMapping = segment->audio->getEndpointMapping(); |
| 917 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 918 | auto videoSegment = std::make_shared<VideoSegment>(); |
| 919 | videoSegment->quality = videoData->quality; |
| 920 | if (part->result->data.empty()) { |
| 921 | RTC_LOG(LS_INFO) << "Video part " << segment->timestamp << " is empty"; |
| 922 | } |
| 923 | videoSegment->part = std::make_shared<VideoStreamingPart>(std::move(part->result->data), VideoStreamingPart::ContentType::Video); |
| 924 | segment->video.push_back(videoSegment); |
| 925 | } else if (const auto videoData = absl::get_if<PendingUnifiedSegmentData>(typeData)) { |
| 926 | auto unifiedSegment = std::make_shared<UnifiedSegment>(); |
| 927 | if (part->result->data.empty()) { |
| 928 | RTC_LOG(LS_INFO) << "Unified part " << segment->timestamp << " is empty"; |
| 929 | } |
| 930 | std::vector<uint8_t> dataCopy = part->result->data; |
| 931 | unifiedSegment->videoPart = std::make_shared<VideoStreamingPart>(std::move(part->result->data), VideoStreamingPart::ContentType::Video); |
| 932 | segment->unified.push_back(unifiedSegment); |
| 933 | segment->unifiedAudio = std::make_shared<VideoStreamingPart>(std::move(dataCopy), VideoStreamingPart::ContentType::Audio); |
| 934 | } |
| 935 | } |
| 936 | _availableSegments.push_back(segment); |
| 937 |
| 938 | shouldRequestMoreSegments = true; |
| 939 |
| 940 | _pendingSegments.erase(_pendingSegments.begin() + i); |
| 941 | i--; |
| 942 | } |
| 943 | } |
| 944 |
| 945 | if (minDelayedRequestTimeout < INT32_MAX) { |
| 946 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 947 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 948 | auto strong = weak.lock(); |
| 949 | if (!strong) { |
| 950 | return; |
| 951 | } |
| 952 | strong->checkPendingSegments(); |
| 953 | }, webrtc::TimeDelta::Millis(std::max((int32_t)minDelayedRequestTimeout, 10))); |
| 954 | } |
| 955 |
| 956 | if (shouldRequestMoreSegments) { |
| 957 | requestSegmentsIfNeeded(); |
| 958 | } |
| 959 | } |
| 960 |
| 961 | void beginPartTask(std::shared_ptr<PendingMediaSegmentPart> part, int64_t segmentTimestamp, std::function<void()> completion) { |
| 962 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 963 | const auto weakPart = std::weak_ptr<PendingMediaSegmentPart>(part); |
| 964 |
| 965 | std::function<void(BroadcastPart &&)> handleResult = [weak, weakPart, threads = _threads, completion](BroadcastPart &&part) { |
| 966 | threads->getMediaThread()->PostTask([weak, weakPart, part = std::move(part), completion]() mutable { |
| 967 | auto strong = weak.lock(); |
| 968 | if (!strong) { |
| 969 | return; |
| 970 | } |
| 971 |
| 972 | auto pendingPart = weakPart.lock(); |
| 973 | if (!pendingPart) { |
| 974 | return; |
| 975 | } |
| 976 |
| 977 | pendingPart->task.reset(); |
| 978 |
| 979 | switch (part.status) { |
| 980 | case BroadcastPart::Status::Success: { |
| 981 | pendingPart->result = std::make_shared<PendingMediaSegmentPartResult>(std::move(part.data)); |
| 982 | break; |
| 983 | } |
| 984 | case BroadcastPart::Status::NotReady: { |
| 985 | break; |
| 986 | } |
| 987 | case BroadcastPart::Status::ResyncNeeded: { |
| 988 | break; |
| 989 | } |
| 990 | default: { |
| 991 | RTC_FATAL() << "Unknown part.status"; |
| 992 | break; |
| 993 | } |
| 994 | } |
| 995 |
| 996 | completion(); |
| 997 | }); |
| 998 | }; |
| 999 |
| 1000 | const auto typeData = &part->typeData; |
| 1001 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 1002 | part->task = _requestAudioBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, handleResult); |
| 1003 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 1004 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, videoData->channelId, videoData->quality, handleResult); |
| 1005 | } else if (const auto unifiedData = absl::get_if<PendingUnifiedSegmentData>(typeData)) { |
| 1006 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, 1, VideoChannelDescription::Quality::Full, handleResult); |
| 1007 | } |
| 1008 | } |
| 1009 |
| 1010 | void setVolume(uint32_t ssrc, double volume) { |
| 1011 | _volumeBySsrc[ssrc] = volume; |
| 1012 | } |
| 1013 |
| 1014 | void setActiveVideoChannels(std::vector<StreamingMediaContext::VideoChannel> const &videoChannels) { |
| 1015 | if (_isUnifiedBroadcast) { |
| 1016 | return; |
| 1017 | } |
| 1018 | _activeVideoChannels = videoChannels; |
| 1019 |
| 1020 | for (const auto &updatedVideoChannel : _activeVideoChannels) { |
| 1021 | for (const auto &segment : _availableSegments) { |
| 1022 | for (const auto &video : segment->video) { |
| 1023 | if (video->part->getActiveEndpointId() == updatedVideoChannel.endpoint) { |
| 1024 | if (video->quality != updatedVideoChannel.quality) { |
| 1025 | requestPendingVideoQualityUpdate(video, segment->timestamp); |
| 1026 | } |
| 1027 | } |
| 1028 | } |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 |
| 1033 | void addVideoSink(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 1034 | auto it = _videoSinks.find(endpointId); |
| 1035 | if (it == _videoSinks.end()) { |
| 1036 | _videoSinks.insert(std::make_pair(endpointId, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>())); |
| 1037 | } |
| 1038 | _videoSinks[endpointId].push_back(sink); |
| 1039 | } |
| 1040 |
| 1041 | private: |
| 1042 | std::shared_ptr<Threads> _threads; |
| 1043 | bool _isUnifiedBroadcast = false; |
| 1044 | std::function<std::shared_ptr<BroadcastPartTask>(std::function<void(int64_t)>)> _requestCurrentTime; |
| 1045 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, std::function<void(BroadcastPart &&)>)> _requestAudioBroadcastPart; |
| 1046 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, int32_t, VideoChannelDescription::Quality, std::function<void(BroadcastPart &&)>)> _requestVideoBroadcastPart; |
| 1047 | std::function<void(uint32_t, float, bool)> _updateAudioLevel; |
| 1048 |
| 1049 | const int _segmentDuration = 1000; |
| 1050 | const int _segmentBufferDuration = 2000; |
| 1051 |
| 1052 | int64_t _nextSegmentTimestamp = -1; |
| 1053 |
| 1054 | absl::optional<int> _waitForBufferredMillisecondsBeforeRendering; |
| 1055 | std::vector<std::shared_ptr<MediaSegment>> _availableSegments; |
| 1056 | AudioStreamingPartPersistentDecoder _persistentAudioDecoder; |
| 1057 |
| 1058 | std::shared_ptr<BroadcastPartTask> _pendingRequestTimeTask; |
| 1059 | int _pendingRequestTimeDelayTaskId = 0; |
| 1060 | int _nextPendingRequestTimeDelayTaskId = 0; |
| 1061 |
| 1062 | std::vector<std::shared_ptr<PendingMediaSegment>> _pendingSegments; |
| 1063 |
| 1064 | int64_t _playbackReferenceTimestamp = 0; |
| 1065 |
| 1066 | const int _audioRingBufferNumChannels = 2; |
| 1067 | const size_t _audioDataRingBufferMaxSize = 4800 * 8; |
| 1068 | webrtc::Mutex _audioDataMutex; |
| 1069 | SampleRingBuffer _audioRingBuffer; |
| 1070 | std::vector<int16_t> _tempAudioBuffer; |
| 1071 | std::vector<int16_t> _stereoShuffleBuffer; |
| 1072 | webrtc::FrameCombiner _audioFrameCombiner; |
| 1073 | std::map<uint32_t, std::unique_ptr<SparseVad>> _audioVadMap; |
| 1074 |
| 1075 | std::map<uint32_t, double> _volumeBySsrc; |
| 1076 | std::vector<StreamingMediaContext::VideoChannel> _activeVideoChannels; |
| 1077 | std::map<std::string, std::shared_ptr<VideoStreamingSharedState>> _sharedVideoStateByEndpointId; |
| 1078 | std::map<std::string, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>> _videoSinks; |
| 1079 |
| 1080 | std::map<std::string, int32_t> _currentEndpointMapping; |
| 1081 |
| 1082 | std::shared_ptr<PlatformContext> _platformContext; |
| 1083 | }; |
| 1084 |
| 1085 | StreamingMediaContext::StreamingMediaContext(StreamingMediaContextArguments &&arguments) { |
| 1086 | _private = std::make_shared<StreamingMediaContextPrivate>(std::move(arguments)); |
| 1087 | _private->start(); |
| 1088 | } |
| 1089 |
| 1090 | StreamingMediaContext::~StreamingMediaContext() { |
| 1091 | } |
| 1092 |
| 1093 | void StreamingMediaContext::setActiveVideoChannels(std::vector<VideoChannel> const &videoChannels) { |
| 1094 | _private->setActiveVideoChannels(videoChannels); |
| 1095 | } |
| 1096 |
| 1097 | void StreamingMediaContext::setVolume(uint32_t ssrc, double volume) { |
| 1098 | _private->setVolume(ssrc, volume); |
| 1099 | } |
| 1100 |
| 1101 | void StreamingMediaContext::addVideoSink(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 1102 | _private->addVideoSink(endpointId, sink); |
| 1103 | } |
| 1104 |
| 1105 | void StreamingMediaContext::getAudio(int16_t *audio_samples, const size_t num_samples, const size_t num_channels, const uint32_t samples_per_sec) { |
| 1106 | _private->getAudio(audio_samples, num_samples, num_channels, samples_per_sec); |
| 1107 | } |
| 1108 |
| 1109 | } |
| 1110 |