Jonas Oreland | 6d83592 | 2019-03-18 10:59:40 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | #include "media/engine/unhandled_packets_buffer.h" |
| 12 | #include "rtc_base/logging.h" |
| 13 | #include "rtc_base/strings/string_builder.h" |
| 14 | |
| 15 | namespace cricket { |
| 16 | |
| 17 | UnhandledPacketsBuffer::UnhandledPacketsBuffer() { |
| 18 | buffer_.reserve(kMaxStashedPackets); |
| 19 | } |
| 20 | |
| 21 | UnhandledPacketsBuffer::~UnhandledPacketsBuffer() = default; |
| 22 | |
| 23 | // Store packet in buffer. |
| 24 | void UnhandledPacketsBuffer::AddPacket(uint32_t ssrc, |
| 25 | int64_t packet_time_us, |
| 26 | rtc::CopyOnWriteBuffer packet) { |
| 27 | if (buffer_.size() < kMaxStashedPackets) { |
| 28 | buffer_.push_back({ssrc, packet_time_us, packet}); |
| 29 | } else { |
| 30 | RTC_DCHECK_LT(insert_pos_, kMaxStashedPackets); |
| 31 | buffer_[insert_pos_] = {ssrc, packet_time_us, packet}; |
| 32 | } |
| 33 | insert_pos_ = (insert_pos_ + 1) % kMaxStashedPackets; |
| 34 | } |
| 35 | |
| 36 | // Backfill |consumer| with all stored packet related |ssrcs|. |
| 37 | void UnhandledPacketsBuffer::BackfillPackets( |
| 38 | rtc::ArrayView<const uint32_t> ssrcs, |
| 39 | std::function<void(uint32_t, int64_t, rtc::CopyOnWriteBuffer)> consumer) { |
| 40 | size_t start; |
| 41 | if (buffer_.size() < kMaxStashedPackets) { |
| 42 | start = 0; |
| 43 | } else { |
| 44 | start = insert_pos_; |
| 45 | } |
| 46 | |
| 47 | size_t count = 0; |
| 48 | std::vector<PacketWithMetadata> remaining; |
| 49 | remaining.reserve(kMaxStashedPackets); |
| 50 | for (size_t i = 0; i < buffer_.size(); ++i) { |
| 51 | const size_t pos = (i + start) % kMaxStashedPackets; |
| 52 | |
| 53 | // One or maybe 2 ssrcs is expected => loop array instead of more elaborate |
| 54 | // scheme. |
| 55 | const uint32_t ssrc = buffer_[pos].ssrc; |
| 56 | if (std::find(ssrcs.begin(), ssrcs.end(), ssrc) != ssrcs.end()) { |
| 57 | ++count; |
| 58 | consumer(ssrc, buffer_[pos].packet_time_us, buffer_[pos].packet); |
| 59 | } else { |
| 60 | remaining.push_back(buffer_[pos]); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | insert_pos_ = 0; // insert_pos is only used when buffer is full. |
| 65 | buffer_.swap(remaining); |
| 66 | } |
| 67 | |
| 68 | } // namespace cricket |