1 /*
2  *  Copyright 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 "pc/jitter_buffer_delay.h"
12 
13 #include "api/sequence_checker.h"
14 #include "rtc_base/checks.h"
15 #include "rtc_base/numerics/safe_conversions.h"
16 #include "rtc_base/numerics/safe_minmax.h"
17 #include "rtc_base/thread.h"
18 
19 namespace {
20 constexpr int kDefaultDelay = 0;
21 constexpr int kMaximumDelayMs = 10000;
22 }  // namespace
23 
24 namespace webrtc {
25 
JitterBufferDelay(rtc::Thread * worker_thread)26 JitterBufferDelay::JitterBufferDelay(rtc::Thread* worker_thread)
27     : signaling_thread_(rtc::Thread::Current()), worker_thread_(worker_thread) {
28   RTC_DCHECK(worker_thread_);
29 }
30 
OnStart(cricket::Delayable * media_channel,uint32_t ssrc)31 void JitterBufferDelay::OnStart(cricket::Delayable* media_channel,
32                                 uint32_t ssrc) {
33   RTC_DCHECK_RUN_ON(signaling_thread_);
34 
35   media_channel_ = media_channel;
36   ssrc_ = ssrc;
37 
38   // Trying to apply cached delay for the audio stream.
39   if (cached_delay_seconds_) {
40     Set(cached_delay_seconds_.value());
41   }
42 }
43 
OnStop()44 void JitterBufferDelay::OnStop() {
45   RTC_DCHECK_RUN_ON(signaling_thread_);
46   // Assume that audio stream is no longer present.
47   media_channel_ = nullptr;
48   ssrc_ = absl::nullopt;
49 }
50 
Set(absl::optional<double> delay_seconds)51 void JitterBufferDelay::Set(absl::optional<double> delay_seconds) {
52   RTC_DCHECK_RUN_ON(worker_thread_);
53 
54   // TODO(kuddai) propagate absl::optional deeper down as default preference.
55   int delay_ms =
56       rtc::saturated_cast<int>(delay_seconds.value_or(kDefaultDelay) * 1000);
57   delay_ms = rtc::SafeClamp(delay_ms, 0, kMaximumDelayMs);
58 
59   cached_delay_seconds_ = delay_seconds;
60   if (media_channel_ && ssrc_) {
61     media_channel_->SetBaseMinimumPlayoutDelayMs(ssrc_.value(), delay_ms);
62   }
63 }
64 
65 }  // namespace webrtc
66