1 /*
2  *  Copyright 2015 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/media_stream_observer.h"
12 
13 #include <string>
14 #include <vector>
15 
16 #include "absl/algorithm/container.h"
17 
18 namespace webrtc {
19 
MediaStreamObserver(MediaStreamInterface * stream)20 MediaStreamObserver::MediaStreamObserver(MediaStreamInterface* stream)
21     : stream_(stream),
22       cached_audio_tracks_(stream->GetAudioTracks()),
23       cached_video_tracks_(stream->GetVideoTracks()) {
24   stream_->RegisterObserver(this);
25 }
26 
~MediaStreamObserver()27 MediaStreamObserver::~MediaStreamObserver() {
28   stream_->UnregisterObserver(this);
29 }
30 
OnChanged()31 void MediaStreamObserver::OnChanged() {
32   AudioTrackVector new_audio_tracks = stream_->GetAudioTracks();
33   VideoTrackVector new_video_tracks = stream_->GetVideoTracks();
34 
35   // Find removed audio tracks.
36   for (const auto& cached_track : cached_audio_tracks_) {
37     if (absl::c_none_of(
38             new_audio_tracks,
39             [cached_track](const AudioTrackVector::value_type& new_track) {
40               return new_track->id() == cached_track->id();
41             })) {
42       SignalAudioTrackRemoved(cached_track.get(), stream_);
43     }
44   }
45 
46   // Find added audio tracks.
47   for (const auto& new_track : new_audio_tracks) {
48     if (absl::c_none_of(
49             cached_audio_tracks_,
50             [new_track](const AudioTrackVector::value_type& cached_track) {
51               return new_track->id() == cached_track->id();
52             })) {
53       SignalAudioTrackAdded(new_track.get(), stream_);
54     }
55   }
56 
57   // Find removed video tracks.
58   for (const auto& cached_track : cached_video_tracks_) {
59     if (absl::c_none_of(
60             new_video_tracks,
61             [cached_track](const VideoTrackVector::value_type& new_track) {
62               return new_track->id() == cached_track->id();
63             })) {
64       SignalVideoTrackRemoved(cached_track.get(), stream_);
65     }
66   }
67 
68   // Find added video tracks.
69   for (const auto& new_track : new_video_tracks) {
70     if (absl::c_none_of(
71             cached_video_tracks_,
72             [new_track](const VideoTrackVector::value_type& cached_track) {
73               return new_track->id() == cached_track->id();
74             })) {
75       SignalVideoTrackAdded(new_track.get(), stream_);
76     }
77   }
78 
79   cached_audio_tracks_ = new_audio_tracks;
80   cached_video_tracks_ = new_video_tracks;
81 }
82 
83 }  // namespace webrtc
84