| 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_with_level.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 PendingVideoSegmentData { |
| 27 | int32_t channelId = 0; |
| 28 | VideoChannelDescription::Quality quality = VideoChannelDescription::Quality::Thumbnail; |
| 29 |
| 30 | PendingVideoSegmentData(int32_t channelId_, VideoChannelDescription::Quality quality_) : |
| 31 | channelId(channelId_), |
| 32 | quality(quality_) { |
| 33 | } |
| 34 | }; |
| 35 |
| 36 | struct PendingMediaSegmentPartResult { |
| 37 | std::vector<uint8_t> data; |
| 38 |
| 39 | explicit PendingMediaSegmentPartResult(std::vector<uint8_t> &&data_) : |
| 40 | data(std::move(data_)) { |
| 41 | } |
| 42 | }; |
| 43 |
| 44 | struct PendingMediaSegmentPart { |
| 45 | absl::variant<PendingAudioSegmentData, PendingVideoSegmentData> typeData; |
| 46 |
| 47 | int64_t minRequestTimestamp = 0; |
| 48 |
| 49 | std::shared_ptr<BroadcastPartTask> task; |
| 50 | std::shared_ptr<PendingMediaSegmentPartResult> result; |
| 51 | }; |
| 52 |
| 53 | struct PendingMediaSegment { |
| 54 | int64_t timestamp = 0; |
| 55 | std::vector<std::shared_ptr<PendingMediaSegmentPart>> parts; |
| 56 | }; |
| 57 |
| 58 | struct VideoSegment { |
| 59 | VideoChannelDescription::Quality quality; |
| 60 | std::shared_ptr<VideoStreamingPart> part; |
| 61 | double lastFramePts = -1.0; |
| 62 | int _displayedFrames = 0; |
| 63 | bool isPlaying = false; |
| 64 | std::shared_ptr<PendingMediaSegmentPart> pendingVideoQualityUpdatePart; |
| 65 | }; |
| 66 |
| 67 | struct MediaSegment { |
| 68 | int64_t timestamp = 0; |
| 69 | int64_t duration = 0; |
| 70 | std::shared_ptr<AudioStreamingPart> audio; |
| 71 | std::vector<std::shared_ptr<VideoSegment>> video; |
| 72 | }; |
| 73 |
| 74 | class SampleRingBuffer { |
| 75 | public: |
| 76 | SampleRingBuffer(size_t size) { |
| 77 | _buffer = WebRtc_CreateBuffer(size, sizeof(int16_t)); |
| 78 | } |
| 79 |
| 80 | ~SampleRingBuffer() { |
| 81 | if (_buffer) { |
| 82 | WebRtc_FreeBuffer(_buffer); |
| 83 | } |
| 84 | } |
| 85 |
| 86 | size_t availableForWriting() { |
| 87 | return WebRtc_available_write(_buffer); |
| 88 | } |
| 89 |
| 90 | size_t write(int16_t const *samples, size_t count) { |
| 91 | return WebRtc_WriteBuffer(_buffer, samples, count); |
| 92 | } |
| 93 |
| 94 | size_t read(int16_t *samples, size_t count) { |
| 95 | return WebRtc_ReadBuffer(_buffer, nullptr, samples, count); |
| 96 | } |
| 97 |
| 98 | private: |
| 99 | RingBuffer *_buffer = nullptr; |
| 100 | }; |
| 101 |
| 102 | static const int kVadResultHistoryLength = 8; |
| 103 |
| 104 | class VadHistory { |
| 105 | private: |
| 106 | float _vadResultHistory[kVadResultHistoryLength]; |
| 107 |
| 108 | public: |
| 109 | VadHistory() { |
| 110 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 111 | _vadResultHistory[i] = 0.0f; |
| 112 | } |
| 113 | } |
| 114 |
| 115 | ~VadHistory() { |
| 116 | } |
| 117 |
| 118 | bool update(float vadProbability) { |
| 119 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 120 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 121 | } |
| 122 | _vadResultHistory[kVadResultHistoryLength - 1] = vadProbability; |
| 123 |
| 124 | float movingAverage = 0.0f; |
| 125 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 126 | movingAverage += _vadResultHistory[i]; |
| 127 | } |
| 128 | movingAverage /= (float)kVadResultHistoryLength; |
| 129 |
| 130 | bool vadResult = false; |
| 131 | if (movingAverage > 0.8f) { |
| 132 | vadResult = true; |
| 133 | } |
| 134 |
| 135 | return vadResult; |
| 136 | } |
| 137 | }; |
| 138 |
| 139 | class CombinedVad { |
| 140 | private: |
| 141 | std::unique_ptr<webrtc::VadLevelAnalyzer> _vadWithLevel; |
| 142 | VadHistory _history; |
| 143 |
| 144 | public: |
| 145 | CombinedVad() { |
| 146 | _vadWithLevel = std::make_unique<webrtc::VadLevelAnalyzer>(500, webrtc::GetAvailableCpuFeatures()); |
| 147 | } |
| 148 |
| 149 | ~CombinedVad() { |
| 150 | } |
| 151 |
| 152 | bool update(webrtc::AudioBuffer *buffer) { |
| 153 | if (buffer->num_channels() <= 0) { |
| 154 | return _history.update(0.0f); |
| 155 | } |
| 156 | webrtc::AudioFrameView<float> frameView(buffer->channels(), buffer->num_channels(), buffer->num_frames()); |
| 157 | float peak = 0.0f; |
| 158 | for (const auto &x : frameView.channel(0)) { |
| 159 | peak = std::max(std::fabs(x), peak); |
| 160 | } |
| 161 | if (peak <= 0.01f) { |
| 162 | return _history.update(false); |
| 163 | } |
| 164 |
| 165 | auto result = _vadWithLevel->AnalyzeFrame(frameView); |
| 166 |
| 167 | return _history.update(result.speech_probability); |
| 168 | } |
| 169 |
| 170 | bool update() { |
| 171 | return _history.update(0.0f); |
| 172 | } |
| 173 | }; |
| 174 |
| 175 | class SparseVad { |
| 176 | public: |
| 177 | SparseVad() { |
| 178 | } |
| 179 |
| 180 | std::pair<float, bool> update(webrtc::AudioBuffer *buffer) { |
| 181 | _sampleCount += buffer->num_frames(); |
| 182 | if (_sampleCount >= 400) { |
| 183 | _sampleCount = 0; |
| 184 | _currentValue = _vad.update(buffer); |
| 185 | } |
| 186 |
| 187 | float currentPeak = 0.0; |
| 188 | float *samples = buffer->channels()[0]; |
| 189 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 190 | float sample = samples[i]; |
| 191 | if (sample < 0.0f) { |
| 192 | sample = -sample; |
| 193 | } |
| 194 | if (_peak < sample) { |
| 195 | _peak = sample; |
| 196 | } |
| 197 | if (currentPeak < sample) { |
| 198 | currentPeak = sample; |
| 199 | } |
| 200 | _peakCount += 1; |
| 201 | } |
| 202 |
| 203 | if (_peakCount >= 4400) { |
| 204 | float norm = 8000.0f; |
| 205 | _currentLevel = ((float)(_peak)) / norm; |
| 206 | _peak = 0; |
| 207 | _peakCount = 0; |
| 208 | } |
| 209 |
| 210 | return std::make_pair(_currentLevel, _currentValue); |
| 211 | } |
| 212 |
| 213 | private: |
| 214 | CombinedVad _vad; |
| 215 | bool _currentValue = false; |
| 216 | size_t _sampleCount = 0; |
| 217 |
| 218 | int _peakCount = 0; |
| 219 | float _peak = 0.0; |
| 220 | float _currentLevel = 0.0; |
| 221 | }; |
| 222 |
| 223 | } |
| 224 |
| 225 | class StreamingMediaContextPrivate : public std::enable_shared_from_this<StreamingMediaContextPrivate> { |
| 226 | public: |
| 227 | StreamingMediaContextPrivate(StreamingMediaContext::StreamingMediaContextArguments &&arguments) : |
| 228 | _threads(arguments.threads), |
| 229 | _requestCurrentTime(arguments.requestCurrentTime), |
| 230 | _requestAudioBroadcastPart(arguments.requestAudioBroadcastPart), |
| 231 | _requestVideoBroadcastPart(arguments.requestVideoBroadcastPart), |
| 232 | _updateAudioLevel(arguments.updateAudioLevel), |
| 233 | _audioRingBuffer(_audioDataRingBufferMaxSize), |
| 234 | _audioFrameCombiner(false), |
| 235 | _platformContext(arguments.platformContext) { |
| 236 | } |
| 237 |
| 238 | ~StreamingMediaContextPrivate() { |
| 239 | } |
| 240 |
| 241 | void start() { |
| 242 | beginRenderTimer(0); |
| 243 | } |
| 244 |
| 245 | void beginRenderTimer(int timeoutMs) { |
| 246 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 247 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 248 | auto strong = weak.lock(); |
| 249 | if (!strong) { |
| 250 | return; |
| 251 | } |
| 252 |
| 253 | strong->render(); |
| 254 |
| 255 | strong->beginRenderTimer((int)(1.0 * 1000.0 / 120.0)); |
| 256 | }, timeoutMs); |
| 257 | } |
| 258 |
| 259 | void render() { |
| 260 | int64_t absoluteTimestamp = rtc::TimeMillis(); |
| 261 |
| 262 | while (true) { |
| 263 | if (_waitForBufferredMillisecondsBeforeRendering) { |
| 264 | if (getAvailableBufferDuration() < _waitForBufferredMillisecondsBeforeRendering.value()) { |
| 265 | break; |
| 266 | } else { |
| 267 | _waitForBufferredMillisecondsBeforeRendering = absl::nullopt; |
| 268 | } |
| 269 | } |
| 270 |
| 271 | if (_availableSegments.empty()) { |
| 272 | _playbackReferenceTimestamp = 0; |
| 273 |
| 274 | _waitForBufferredMillisecondsBeforeRendering = _segmentBufferDuration + _segmentDuration; |
| 275 |
| 276 | break; |
| 277 | } |
| 278 |
| 279 | if (_playbackReferenceTimestamp == 0) { |
| 280 | _playbackReferenceTimestamp = absoluteTimestamp; |
| 281 | } |
| 282 |
| 283 | double relativeTimestamp = ((double)(absoluteTimestamp - _playbackReferenceTimestamp)) / 1000.0; |
| 284 |
| 285 | auto segment = _availableSegments[0]; |
| 286 | double segmentDuration = ((double)segment->duration) / 1000.0; |
| 287 |
| 288 | for (auto &videoSegment : segment->video) { |
| 289 | videoSegment->isPlaying = true; |
| 290 | cancelPendingVideoQualityUpdate(videoSegment); |
| 291 |
| 292 | auto frame = videoSegment->part->getFrameAtRelativeTimestamp(relativeTimestamp); |
| 293 | if (frame) { |
| 294 | if (videoSegment->lastFramePts != frame->pts) { |
| 295 | videoSegment->lastFramePts = frame->pts; |
| 296 | videoSegment->_displayedFrames += 1; |
| 297 |
| 298 | auto sinkList = _videoSinks.find(frame->endpointId); |
| 299 | if (sinkList != _videoSinks.end()) { |
| 300 | for (const auto &weakSink : sinkList->second) { |
| 301 | auto sink = weakSink.lock(); |
| 302 | if (sink) { |
| 303 | sink->OnFrame(frame->frame); |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 |
| 311 | if (segment->audio) { |
| 312 | const auto available = [&] { |
| 313 | _audioDataMutex.Lock(); |
| 314 | const auto result = (_audioRingBuffer.availableForWriting() >= 480); |
| 315 | _audioDataMutex.Unlock(); |
| 316 |
| 317 | return result; |
| 318 | }; |
| 319 | while (available()) { |
| 320 | auto audioChannels = segment->audio->get10msPerChannel(); |
| 321 | if (audioChannels.empty()) { |
| 322 | break; |
| 323 | } |
| 324 |
| 325 | std::vector<webrtc::AudioFrame *> audioFrames; |
| 326 |
| 327 | for (const auto &audioChannel : audioChannels) { |
| 328 | webrtc::AudioFrame *frame = new webrtc::AudioFrame(); |
| 329 | frame->UpdateFrame(0, audioChannel.pcmData.data(), audioChannel.pcmData.size(), 48000, webrtc::AudioFrame::SpeechType::kNormalSpeech, webrtc::AudioFrame::VADActivity::kVadActive); |
| 330 |
| 331 | auto volumeIt = _volumeBySsrc.find(audioChannel.ssrc); |
| 332 | if (volumeIt != _volumeBySsrc.end()) { |
| 333 | double outputGain = volumeIt->second; |
| 334 | if (outputGain < 0.99f || outputGain > 1.01f) { |
| 335 | webrtc::AudioFrameOperations::ScaleWithSat(outputGain, frame); |
| 336 | } |
| 337 | } |
| 338 |
| 339 | audioFrames.push_back(frame); |
| 340 | processAudioLevel(audioChannel.ssrc, audioChannel.pcmData); |
| 341 | } |
| 342 |
| 343 | webrtc::AudioFrame frameOut; |
| 344 | _audioFrameCombiner.Combine(audioFrames, 1, 48000, audioFrames.size(), &frameOut); |
| 345 |
| 346 | for (webrtc::AudioFrame *frame : audioFrames) { |
| 347 | delete frame; |
| 348 | } |
| 349 |
| 350 | _audioDataMutex.Lock(); |
| 351 | _audioRingBuffer.write(frameOut.data(), frameOut.samples_per_channel()); |
| 352 | _audioDataMutex.Unlock(); |
| 353 | } |
| 354 | } |
| 355 |
| 356 | if (relativeTimestamp >= segmentDuration) { |
| 357 | _playbackReferenceTimestamp += segment->duration; |
| 358 |
| 359 | if (segment->audio && segment->audio->getRemainingMilliseconds() > 0) { |
| 360 | RTC_LOG(LS_INFO) << "render: discarding " << segment->audio->getRemainingMilliseconds() << " ms of audio at the end of a segment"; |
| 361 | } |
| 362 | if (!segment->video.empty()) { |
| 363 | if (segment->video[0]->part->getActiveEndpointId()) { |
| 364 | RTC_LOG(LS_INFO) << "render: discarding video frames at the end of a segment (displayed " << segment->video[0]->_displayedFrames << " frames)"; |
| 365 | } |
| 366 | } |
| 367 |
| 368 | _availableSegments.erase(_availableSegments.begin()); |
| 369 | } |
| 370 |
| 371 | break; |
| 372 | } |
| 373 |
| 374 | requestSegmentsIfNeeded(); |
| 375 | checkPendingSegments(); |
| 376 | } |
| 377 |
| 378 | void processAudioLevel(uint32_t ssrc, std::vector<int16_t> const &samples) { |
| 379 | if (!_updateAudioLevel) { |
| 380 | return; |
| 381 | } |
| 382 |
| 383 | webrtc::AudioBuffer buffer(48000, 1, 48000, 1, 48000, 1); |
| 384 | webrtc::StreamConfig config(48000, 1); |
| 385 | buffer.CopyFrom(samples.data(), config); |
| 386 |
| 387 | std::pair<float, bool> vadResult = std::make_pair(0.0f, false); |
| 388 | auto vad = _audioVadMap.find(ssrc); |
| 389 | if (vad == _audioVadMap.end()) { |
| 390 | auto newVad = std::make_unique<SparseVad>(); |
| 391 | vadResult = newVad->update(&buffer); |
| 392 | _audioVadMap.insert(std::make_pair(ssrc, std::move(newVad))); |
| 393 | } else { |
| 394 | vadResult = vad->second->update(&buffer); |
| 395 | } |
| 396 |
| 397 | _updateAudioLevel(ssrc, vadResult.first, vadResult.second); |
| 398 | } |
| 399 |
| 400 | void getAudio(int16_t *audio_samples, const size_t num_samples, const size_t num_channels, const uint32_t samples_per_sec) { |
| 401 | int16_t *buffer = nullptr; |
| 402 |
| 403 | if (num_channels == 1) { |
| 404 | buffer = audio_samples; |
| 405 | } else { |
| 406 | if (_tempAudioBuffer.size() < num_samples) { |
| 407 | _tempAudioBuffer.resize(num_samples); |
| 408 | } |
| 409 | buffer = _tempAudioBuffer.data(); |
| 410 | } |
| 411 |
| 412 | _audioDataMutex.Lock(); |
| 413 | size_t readSamples = _audioRingBuffer.read(buffer, num_samples); |
| 414 | _audioDataMutex.Unlock(); |
| 415 |
| 416 | if (num_channels != 1) { |
| 417 | for (size_t sampleIndex = 0; sampleIndex < readSamples; sampleIndex++) { |
| 418 | for (size_t channelIndex = 0; channelIndex < num_channels; channelIndex++) { |
| 419 | audio_samples[sampleIndex * num_channels + channelIndex] = _tempAudioBuffer[sampleIndex]; |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | if (readSamples < num_samples) { |
| 424 | memset(audio_samples + readSamples * num_channels, 0, (num_samples - readSamples) * num_channels * sizeof(int16_t)); |
| 425 | } |
| 426 | } |
| 427 |
| 428 | int64_t getAvailableBufferDuration() { |
| 429 | int64_t result = 0; |
| 430 |
| 431 | for (const auto &segment : _availableSegments) { |
| 432 | result += segment->duration; |
| 433 | } |
| 434 |
| 435 | return (int)result; |
| 436 | } |
| 437 |
| 438 | void discardAllPendingSegments() { |
| 439 | for (size_t i = 0; i < _pendingSegments.size(); i++) { |
| 440 | for (const auto &it : _pendingSegments[i]->parts) { |
| 441 | if (it->task) { |
| 442 | it->task->cancel(); |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 |
| 447 | _pendingSegments.clear(); |
| 448 | } |
| 449 |
| 450 | void requestSegmentsIfNeeded() { |
| 451 | while (true) { |
| 452 | if (_nextSegmentTimestamp == 0) { |
| 453 | if (_pendingSegments.size() >= 1) { |
| 454 | break; |
| 455 | } |
| 456 | } else { |
| 457 | int64_t availableAndRequestedSegmentsDuration = 0; |
| 458 | availableAndRequestedSegmentsDuration += getAvailableBufferDuration(); |
| 459 | availableAndRequestedSegmentsDuration += _pendingSegments.size() * _segmentDuration; |
| 460 |
| 461 | if (availableAndRequestedSegmentsDuration > _segmentBufferDuration) { |
| 462 | break; |
| 463 | } |
| 464 | } |
| 465 |
| 466 | auto pendingSegment = std::make_shared<PendingMediaSegment>(); |
| 467 | pendingSegment->timestamp = _nextSegmentTimestamp; |
| 468 |
| 469 | if (_nextSegmentTimestamp != 0) { |
| 470 | _nextSegmentTimestamp += _segmentDuration; |
| 471 | } |
| 472 |
| 473 | auto audio = std::make_shared<PendingMediaSegmentPart>(); |
| 474 | audio->typeData = PendingAudioSegmentData(); |
| 475 | audio->minRequestTimestamp = 0; |
| 476 | pendingSegment->parts.push_back(audio); |
| 477 |
| 478 | for (const auto &videoChannel : _activeVideoChannels) { |
| 479 | auto channelIdIt = _currentEndpointMapping.find(videoChannel.endpoint); |
| 480 | if (channelIdIt == _currentEndpointMapping.end()) { |
| 481 | continue; |
| 482 | } |
| 483 |
| 484 | int32_t channelId = channelIdIt->second + 1; |
| 485 |
| 486 | auto video = std::make_shared<PendingMediaSegmentPart>(); |
| 487 | video->typeData = PendingVideoSegmentData(channelId, videoChannel.quality); |
| 488 | video->minRequestTimestamp = 0; |
| 489 | pendingSegment->parts.push_back(video); |
| 490 | } |
| 491 |
| 492 | _pendingSegments.push_back(pendingSegment); |
| 493 |
| 494 | if (_nextSegmentTimestamp == 0) { |
| 495 | break; |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 |
| 500 | void requestPendingVideoQualityUpdate(std::shared_ptr<VideoSegment> segment, int64_t timestamp) { |
| 501 | if (segment->isPlaying) { |
| 502 | return; |
| 503 | } |
| 504 | auto segmentEndpointId = segment->part->getActiveEndpointId(); |
| 505 | if (!segmentEndpointId) { |
| 506 | return; |
| 507 | } |
| 508 |
| 509 | absl::optional<int32_t> updatedChannelId; |
| 510 | absl::optional<VideoChannelDescription::Quality> updatedQuality; |
| 511 |
| 512 | for (const auto &videoChannel : _activeVideoChannels) { |
| 513 | auto channelIdIt = _currentEndpointMapping.find(videoChannel.endpoint); |
| 514 | if (channelIdIt == _currentEndpointMapping.end()) { |
| 515 | continue; |
| 516 | } |
| 517 |
| 518 | updatedChannelId = channelIdIt->second + 1; |
| 519 | updatedQuality = videoChannel.quality; |
| 520 | } |
| 521 |
| 522 | if (updatedChannelId && updatedQuality) { |
| 523 | if (segment->pendingVideoQualityUpdatePart) { |
| 524 | const auto typeData = &segment->pendingVideoQualityUpdatePart->typeData; |
| 525 | if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 526 | if (videoData->channelId == updatedChannelId.value() && videoData->quality == updatedQuality.value()) { |
| 527 | return; |
| 528 | } |
| 529 | } |
| 530 | cancelPendingVideoQualityUpdate(segment); |
| 531 | } |
| 532 |
| 533 | auto video = std::make_shared<PendingMediaSegmentPart>(); |
| 534 |
| 535 | video->typeData = PendingVideoSegmentData(updatedChannelId.value(), updatedQuality.value()); |
| 536 | video->minRequestTimestamp = 0; |
| 537 |
| 538 | segment->pendingVideoQualityUpdatePart = video; |
| 539 |
| 540 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 541 | const auto weakSegment = std::weak_ptr<VideoSegment>(segment); |
| 542 | beginPartTask(video, timestamp, [weak, weakSegment]() { |
| 543 | auto strong = weak.lock(); |
| 544 | if (!strong) { |
| 545 | return; |
| 546 | } |
| 547 |
| 548 | auto strongSegment = weakSegment.lock(); |
| 549 | if (!strongSegment) { |
| 550 | return; |
| 551 | } |
| 552 |
| 553 | if (!strongSegment->pendingVideoQualityUpdatePart) { |
| 554 | return; |
| 555 | } |
| 556 |
| 557 | auto result = strongSegment->pendingVideoQualityUpdatePart->result; |
| 558 | if (result) { |
| 559 | strongSegment->part = std::make_shared<VideoStreamingPart>(std::move(result->data)); |
| 560 | } |
| 561 |
| 562 | strongSegment->pendingVideoQualityUpdatePart.reset(); |
| 563 | }); |
| 564 | } |
| 565 | } |
| 566 |
| 567 | void cancelPendingVideoQualityUpdate(std::shared_ptr<VideoSegment> segment) { |
| 568 | if (!segment->pendingVideoQualityUpdatePart) { |
| 569 | return; |
| 570 | } |
| 571 |
| 572 | if (segment->pendingVideoQualityUpdatePart->task) { |
| 573 | segment->pendingVideoQualityUpdatePart->task->cancel(); |
| 574 | } |
| 575 |
| 576 | segment->pendingVideoQualityUpdatePart.reset(); |
| 577 | } |
| 578 |
| 579 | void checkPendingSegments() { |
| 580 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 581 |
| 582 | int64_t absoluteTimestamp = rtc::TimeMillis(); |
| 583 | int64_t minDelayedRequestTimeout = INT_MAX; |
| 584 |
| 585 | bool shouldRequestMoreSegments = false; |
| 586 |
| 587 | for (int i = 0; i < _pendingSegments.size(); i++) { |
| 588 | auto pendingSegment = _pendingSegments[i]; |
| 589 | auto segmentTimestamp = pendingSegment->timestamp; |
| 590 |
| 591 | bool allPartsDone = true; |
| 592 |
| 593 | for (auto &part : pendingSegment->parts) { |
| 594 | if (!part->result) { |
| 595 | allPartsDone = false; |
| 596 | } |
| 597 |
| 598 | if (!part->result && !part->task) { |
| 599 | if (part->minRequestTimestamp != 0) { |
| 600 | if (i != 0) { |
| 601 | continue; |
| 602 | } |
| 603 | if (part->minRequestTimestamp > absoluteTimestamp) { |
| 604 | minDelayedRequestTimeout = std::min(minDelayedRequestTimeout, part->minRequestTimestamp - absoluteTimestamp); |
| 605 |
| 606 | continue; |
| 607 | } |
| 608 | } |
| 609 |
| 610 | const auto weakSegment = std::weak_ptr<PendingMediaSegment>(pendingSegment); |
| 611 | const auto weakPart = std::weak_ptr<PendingMediaSegmentPart>(part); |
| 612 |
| 613 | std::function<void(BroadcastPart &&)> handleResult = [weak, weakSegment, weakPart, threads = _threads, segmentTimestamp](BroadcastPart &&part) { |
| 614 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, weakSegment, weakPart, part = std::move(part), segmentTimestamp]() mutable { |
| 615 | auto strong = weak.lock(); |
| 616 | if (!strong) { |
| 617 | return; |
| 618 | } |
| 619 | auto strongSegment = weakSegment.lock(); |
| 620 | if (!strongSegment) { |
| 621 | return; |
| 622 | } |
| 623 |
| 624 | auto pendingPart = weakPart.lock(); |
| 625 | if (!pendingPart) { |
| 626 | return; |
| 627 | } |
| 628 |
| 629 | pendingPart->task.reset(); |
| 630 |
| 631 | switch (part.status) { |
| 632 | case BroadcastPart::Status::Success: { |
| 633 | pendingPart->result = std::make_shared<PendingMediaSegmentPartResult>(std::move(part.data)); |
| 634 | if (strong->_nextSegmentTimestamp == 0) { |
| 635 | strong->_nextSegmentTimestamp = part.timestampMilliseconds + strong->_segmentDuration; |
| 636 | } |
| 637 | strong->checkPendingSegments(); |
| 638 | break; |
| 639 | } |
| 640 | case BroadcastPart::Status::NotReady: { |
| 641 | if (segmentTimestamp == 0) { |
| 642 | int64_t responseTimestampMilliseconds = (int64_t)(part.responseTimestamp * 1000.0); |
| 643 | int64_t responseTimestampBoundary = (responseTimestampMilliseconds / strong->_segmentDuration) * strong->_segmentDuration; |
| 644 |
| 645 | strong->_nextSegmentTimestamp = responseTimestampBoundary; |
| 646 | strong->discardAllPendingSegments(); |
| 647 | strong->requestSegmentsIfNeeded(); |
| 648 | strong->checkPendingSegments(); |
| 649 | } else { |
| 650 | pendingPart->minRequestTimestamp = rtc::TimeMillis() + 100; |
| 651 | strong->checkPendingSegments(); |
| 652 | } |
| 653 | break; |
| 654 | } |
| 655 | case BroadcastPart::Status::ResyncNeeded: { |
| 656 | int64_t responseTimestampMilliseconds = (int64_t)(part.responseTimestamp * 1000.0); |
| 657 | int64_t responseTimestampBoundary = (responseTimestampMilliseconds / strong->_segmentDuration) * strong->_segmentDuration; |
| 658 |
| 659 | strong->_nextSegmentTimestamp = responseTimestampBoundary; |
| 660 | strong->discardAllPendingSegments(); |
| 661 | strong->requestSegmentsIfNeeded(); |
| 662 | strong->checkPendingSegments(); |
| 663 |
| 664 | break; |
| 665 | } |
| 666 | default: { |
| 667 | RTC_FATAL() << "Unknown part.status"; |
| 668 | break; |
| 669 | } |
| 670 | } |
| 671 | }); |
| 672 | }; |
| 673 |
| 674 | const auto typeData = &part->typeData; |
| 675 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 676 | part->task = _requestAudioBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, handleResult); |
| 677 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 678 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, videoData->channelId, videoData->quality, handleResult); |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 |
| 683 | if (allPartsDone && i == 0) { |
| 684 | std::shared_ptr<MediaSegment> segment = std::make_shared<MediaSegment>(); |
| 685 | segment->timestamp = pendingSegment->timestamp; |
| 686 | segment->duration = _segmentDuration; |
| 687 | for (auto &part : pendingSegment->parts) { |
| 688 | const auto typeData = &part->typeData; |
| 689 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 690 | segment->audio = std::make_shared<AudioStreamingPart>(std::move(part->result->data)); |
| 691 | _currentEndpointMapping = segment->audio->getEndpointMapping(); |
| 692 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 693 | auto videoSegment = std::make_shared<VideoSegment>(); |
| 694 | videoSegment->quality = videoData->quality; |
| 695 | if (part->result->data.empty()) { |
| 696 | RTC_LOG(LS_INFO) << "Video part " << segment->timestamp << " is empty"; |
| 697 | } |
| 698 | videoSegment->part = std::make_shared<VideoStreamingPart>(std::move(part->result->data)); |
| 699 | segment->video.push_back(videoSegment); |
| 700 | } |
| 701 | } |
| 702 | _availableSegments.push_back(segment); |
| 703 |
| 704 | shouldRequestMoreSegments = true; |
| 705 |
| 706 | _pendingSegments.erase(_pendingSegments.begin() + i); |
| 707 | i--; |
| 708 | } |
| 709 | } |
| 710 |
| 711 | if (minDelayedRequestTimeout < INT32_MAX) { |
| 712 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 713 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 714 | auto strong = weak.lock(); |
| 715 | if (!strong) { |
| 716 | return; |
| 717 | } |
| 718 | strong->checkPendingSegments(); |
| 719 | }, std::max((int32_t)minDelayedRequestTimeout, 10)); |
| 720 | } |
| 721 |
| 722 | if (shouldRequestMoreSegments) { |
| 723 | requestSegmentsIfNeeded(); |
| 724 | } |
| 725 | } |
| 726 |
| 727 | void beginPartTask(std::shared_ptr<PendingMediaSegmentPart> part, int64_t segmentTimestamp, std::function<void()> completion) { |
| 728 | const auto weak = std::weak_ptr<StreamingMediaContextPrivate>(shared_from_this()); |
| 729 | const auto weakPart = std::weak_ptr<PendingMediaSegmentPart>(part); |
| 730 |
| 731 | std::function<void(BroadcastPart &&)> handleResult = [weak, weakPart, threads = _threads, completion](BroadcastPart &&part) { |
| 732 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, weakPart, part = std::move(part), completion]() mutable { |
| 733 | auto strong = weak.lock(); |
| 734 | if (!strong) { |
| 735 | return; |
| 736 | } |
| 737 |
| 738 | auto pendingPart = weakPart.lock(); |
| 739 | if (!pendingPart) { |
| 740 | return; |
| 741 | } |
| 742 |
| 743 | pendingPart->task.reset(); |
| 744 |
| 745 | switch (part.status) { |
| 746 | case BroadcastPart::Status::Success: { |
| 747 | pendingPart->result = std::make_shared<PendingMediaSegmentPartResult>(std::move(part.data)); |
| 748 | break; |
| 749 | } |
| 750 | case BroadcastPart::Status::NotReady: { |
| 751 | break; |
| 752 | } |
| 753 | case BroadcastPart::Status::ResyncNeeded: { |
| 754 | break; |
| 755 | } |
| 756 | default: { |
| 757 | RTC_FATAL() << "Unknown part.status"; |
| 758 | break; |
| 759 | } |
| 760 | } |
| 761 |
| 762 | completion(); |
| 763 | }); |
| 764 | }; |
| 765 |
| 766 | const auto typeData = &part->typeData; |
| 767 | if (const auto audioData = absl::get_if<PendingAudioSegmentData>(typeData)) { |
| 768 | part->task = _requestAudioBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, handleResult); |
| 769 | } else if (const auto videoData = absl::get_if<PendingVideoSegmentData>(typeData)) { |
| 770 | part->task = _requestVideoBroadcastPart(_platformContext, segmentTimestamp, _segmentDuration, videoData->channelId, videoData->quality, handleResult); |
| 771 | } |
| 772 | } |
| 773 |
| 774 | void setVolume(uint32_t ssrc, double volume) { |
| 775 | _volumeBySsrc[ssrc] = volume; |
| 776 | } |
| 777 |
| 778 | void setActiveVideoChannels(std::vector<StreamingMediaContext::VideoChannel> const &videoChannels) { |
| 779 | _activeVideoChannels = videoChannels; |
| 780 |
| 781 | /*#if DEBUG |
| 782 | for (auto &updatedVideoChannel : _activeVideoChannels) { |
| 783 | if (updatedVideoChannel.quality == VideoChannelDescription::Quality::Medium) { |
| 784 | updatedVideoChannel.quality = VideoChannelDescription::Quality::Thumbnail; |
| 785 | } |
| 786 | } |
| 787 | #endif*/ |
| 788 |
| 789 | for (const auto &updatedVideoChannel : _activeVideoChannels) { |
| 790 | for (const auto &segment : _availableSegments) { |
| 791 | for (const auto &video : segment->video) { |
| 792 | if (video->part->getActiveEndpointId() == updatedVideoChannel.endpoint) { |
| 793 | if (video->quality != updatedVideoChannel.quality) { |
| 794 | requestPendingVideoQualityUpdate(video, segment->timestamp); |
| 795 | } |
| 796 | } |
| 797 | } |
| 798 | } |
| 799 | } |
| 800 | } |
| 801 |
| 802 | void addVideoSink(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 803 | auto it = _videoSinks.find(endpointId); |
| 804 | if (it == _videoSinks.end()) { |
| 805 | _videoSinks.insert(std::make_pair(endpointId, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>())); |
| 806 | } |
| 807 | _videoSinks[endpointId].push_back(sink); |
| 808 | } |
| 809 |
| 810 | private: |
| 811 | std::shared_ptr<Threads> _threads; |
| 812 | std::function<std::shared_ptr<BroadcastPartTask>(std::function<void(int64_t)>)> _requestCurrentTime; |
| 813 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, std::function<void(BroadcastPart &&)>)> _requestAudioBroadcastPart; |
| 814 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, int32_t, VideoChannelDescription::Quality, std::function<void(BroadcastPart &&)>)> _requestVideoBroadcastPart; |
| 815 | std::function<void(uint32_t, float, bool)> _updateAudioLevel; |
| 816 |
| 817 | const int _segmentDuration = 1000; |
| 818 | const int _segmentBufferDuration = 2000; |
| 819 |
| 820 | int64_t _nextSegmentTimestamp = 0; |
| 821 |
| 822 | absl::optional<int> _waitForBufferredMillisecondsBeforeRendering; |
| 823 | std::vector<std::shared_ptr<MediaSegment>> _availableSegments; |
| 824 |
| 825 | std::vector<std::shared_ptr<PendingMediaSegment>> _pendingSegments; |
| 826 |
| 827 | int64_t _playbackReferenceTimestamp = 0; |
| 828 |
| 829 | const size_t _audioDataRingBufferMaxSize = 4800; |
| 830 | webrtc::Mutex _audioDataMutex; |
| 831 | SampleRingBuffer _audioRingBuffer; |
| 832 | std::vector<int16_t> _tempAudioBuffer; |
| 833 | webrtc::FrameCombiner _audioFrameCombiner; |
| 834 | std::map<uint32_t, std::unique_ptr<SparseVad>> _audioVadMap; |
| 835 |
| 836 | std::map<uint32_t, double> _volumeBySsrc; |
| 837 | std::vector<StreamingMediaContext::VideoChannel> _activeVideoChannels; |
| 838 | std::map<std::string, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>> _videoSinks; |
| 839 |
| 840 | std::map<std::string, int32_t> _currentEndpointMapping; |
| 841 |
| 842 | std::shared_ptr<PlatformContext> _platformContext; |
| 843 | }; |
| 844 |
| 845 | StreamingMediaContext::StreamingMediaContext(StreamingMediaContextArguments &&arguments) { |
| 846 | _private = std::make_shared<StreamingMediaContextPrivate>(std::move(arguments)); |
| 847 | _private->start(); |
| 848 | } |
| 849 |
| 850 | StreamingMediaContext::~StreamingMediaContext() { |
| 851 | } |
| 852 |
| 853 | void StreamingMediaContext::setActiveVideoChannels(std::vector<VideoChannel> const &videoChannels) { |
| 854 | _private->setActiveVideoChannels(videoChannels); |
| 855 | } |
| 856 |
| 857 | void StreamingMediaContext::setVolume(uint32_t ssrc, double volume) { |
| 858 | _private->setVolume(ssrc, volume); |
| 859 | } |
| 860 |
| 861 | void StreamingMediaContext::addVideoSink(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 862 | _private->addVideoSink(endpointId, sink); |
| 863 | } |
| 864 |
| 865 | void StreamingMediaContext::getAudio(int16_t *audio_samples, const size_t num_samples, const size_t num_channels, const uint32_t samples_per_sec) { |
| 866 | _private->getAudio(audio_samples, num_samples, num_channels, samples_per_sec); |
| 867 | } |
| 868 |
| 869 | } |
| 870 |