summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/mediastream/user_media_client.cc
blob: f40e32f2b81c9e46985fda31bfcd8fbff4722729 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/mediastream/user_media_client.h"

#include <stddef.h>
#include <algorithm>
#include <utility>

#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/modules/webrtc/webrtc_logging.h"
#include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h"
#include "third_party/blink/public/web/modules/mediastream/web_media_stream_device_observer.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/modules/mediastream/apply_constraints_processor.h"
#include "third_party/blink/renderer/modules/peerconnection/peer_connection_tracker.h"
#include "third_party/blink/renderer/platform/mediastream/media_constraints.h"
#include "third_party/blink/renderer/platform/mediastream/webrtc_uma_histograms.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"

namespace blink {
namespace {

static int g_next_request_id = 0;

// The histogram counts the number of calls to the JS API
// getUserMedia or getDisplayMedia().
void UpdateAPICount(UserMediaRequest::MediaType media_type) {
  RTCAPIName api_name = RTCAPIName::kGetUserMedia;
  switch (media_type) {
    case UserMediaRequest::MediaType::kUserMedia:
      api_name = RTCAPIName::kGetUserMedia;
      break;
    case UserMediaRequest::MediaType::kDisplayMedia:
      api_name = RTCAPIName::kGetDisplayMedia;
      break;
  }
  UpdateWebRTCMethodCount(api_name);
}

}  // namespace

UserMediaClient::Request::Request(UserMediaRequest* user_media_request)
    : user_media_request_(user_media_request) {
  DCHECK(user_media_request_);
  DCHECK(!apply_constraints_request_);
  DCHECK(web_track_to_stop_.IsNull());
}

UserMediaClient::Request::Request(blink::ApplyConstraintsRequest* request)
    : apply_constraints_request_(request) {
  DCHECK(apply_constraints_request_);
  DCHECK(!user_media_request_);
  DCHECK(web_track_to_stop_.IsNull());
}

UserMediaClient::Request::Request(
    const blink::WebMediaStreamTrack& web_track_to_stop)
    : web_track_to_stop_(web_track_to_stop) {
  DCHECK(!web_track_to_stop_.IsNull());
  DCHECK(!user_media_request_);
  DCHECK(!apply_constraints_request_);
}

UserMediaClient::Request::~Request() = default;

UserMediaRequest* UserMediaClient::Request::MoveUserMediaRequest() {
  auto user_media_request = user_media_request_;
  user_media_request_ = nullptr;
  return user_media_request;
}

UserMediaClient::UserMediaClient(
    LocalFrame* frame,
    UserMediaProcessor* user_media_processor,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : frame_(frame),
      user_media_processor_(user_media_processor),
      apply_constraints_processor_(
          MakeGarbageCollected<ApplyConstraintsProcessor>(
              WTF::BindRepeating(
                  [](UserMediaClient* client)
                      -> mojom::blink::MediaDevicesDispatcherHost* {
                    // |client| is guaranteed to be not null because |client|
                    // owns this ApplyConstraintsProcessor.
                    DCHECK(client);
                    return client->GetMediaDevicesDispatcher();
                  },
                  WrapWeakPersistent(this)),
              std::move(task_runner))) {
  if (frame_) {
    // WrapWeakPersistent is safe because the |frame_| owns UserMediaClient.
    frame_->SetIsCapturingMediaCallback(WTF::BindRepeating(
        [](UserMediaClient* client) { return client && client->IsCapturing(); },
        WrapWeakPersistent(this)));
  }
}

UserMediaClient::UserMediaClient(
    LocalFrame* frame,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : UserMediaClient(
          frame,
          MakeGarbageCollected<UserMediaProcessor>(
              frame,
              WTF::BindRepeating(
                  [](UserMediaClient* client)
                      -> mojom::blink::MediaDevicesDispatcherHost* {
                    // |client| is guaranteed to be not null because |client|
                    // owns this UserMediaProcessor.
                    DCHECK(client);
                    return client->GetMediaDevicesDispatcher();
                  },
                  WrapWeakPersistent(this)),
              frame->GetTaskRunner(blink::TaskType::kInternalMedia)),
          std::move(task_runner)) {}

UserMediaClient::~UserMediaClient() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  // Ensure that ContextDestroyed() gets called before the destructor.
  DCHECK(!is_processing_request_);
}

void UserMediaClient::RequestUserMedia(UserMediaRequest* user_media_request) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(user_media_request);
  DCHECK(user_media_request->Audio() || user_media_request->Video());
  // ownerDocument may be null if we are in a test.
  // In that case, it's OK to not check frame().

  DCHECK(!user_media_request->OwnerDocument() ||
         frame_ == user_media_request->OwnerDocument()->GetFrame());

  // Save histogram data so we can see how much GetUserMedia is used.
  UpdateAPICount(user_media_request->MediaRequestType());

  // TODO(crbug.com/787254): Communicate directly with the
  // PeerConnectionTrackerHost mojo object once it is available from Blink.
  PeerConnectionTracker::GetInstance()->TrackGetUserMedia(user_media_request);

  int request_id = g_next_request_id++;
  blink::WebRtcLogMessage(base::StringPrintf(
      "UMCI::RequestUserMedia({request_id=%d}, {audio constraints=%s}, "
      "{video constraints=%s})",
      request_id,
      user_media_request->AudioConstraints().ToString().Utf8().c_str(),
      user_media_request->VideoConstraints().ToString().Utf8().c_str()));

  // The value returned by HasTransientUserActivation() is used by the browser
  // to make decisions about the permissions UI. Its value can be lost while
  // switching threads, so saving its value here.
  //
  // TODO(mustaq): The description above seems specific to pre-UAv2 stack-based
  // tokens.  Perhaps we don't need to preserve this bit?
  bool has_transient_user_activation = false;
  if (user_media_request->OwnerDocument() &&
      user_media_request->OwnerDocument()->GetFrame()) {
    has_transient_user_activation = user_media_request->OwnerDocument()
                                        ->GetFrame()
                                        ->Frame::HasTransientUserActivation();
  }
  user_media_request->set_request_id(request_id);
  user_media_request->set_has_transient_user_activation(
      has_transient_user_activation);
  pending_request_infos_.push_back(
      MakeGarbageCollected<Request>(user_media_request));
  if (!is_processing_request_)
    MaybeProcessNextRequestInfo();
}

void UserMediaClient::ApplyConstraints(
    blink::ApplyConstraintsRequest* user_media_request) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  pending_request_infos_.push_back(
      MakeGarbageCollected<Request>(user_media_request));
  if (!is_processing_request_)
    MaybeProcessNextRequestInfo();
}

void UserMediaClient::StopTrack(const blink::WebMediaStreamTrack& web_track) {
  pending_request_infos_.push_back(MakeGarbageCollected<Request>(web_track));
  if (!is_processing_request_)
    MaybeProcessNextRequestInfo();
}

bool UserMediaClient::IsCapturing() {
  return user_media_processor_->HasActiveSources();
}

void UserMediaClient::MaybeProcessNextRequestInfo() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (is_processing_request_ || pending_request_infos_.empty())
    return;

  auto current_request = std::move(pending_request_infos_.front());
  pending_request_infos_.pop_front();
  is_processing_request_ = true;

  if (current_request->IsUserMedia()) {
    user_media_processor_->ProcessRequest(
        current_request->MoveUserMediaRequest(),
        WTF::Bind(&UserMediaClient::CurrentRequestCompleted,
                  WrapWeakPersistent(this)));
  } else if (current_request->IsApplyConstraints()) {
    apply_constraints_processor_->ProcessRequest(
        current_request->apply_constraints_request(),
        WTF::Bind(&UserMediaClient::CurrentRequestCompleted,
                  WrapWeakPersistent(this)));
  } else {
    DCHECK(current_request->IsStopTrack());
    blink::WebPlatformMediaStreamTrack* track =
        blink::WebPlatformMediaStreamTrack::GetTrack(
            current_request->web_track_to_stop());
    if (track) {
      track->StopAndNotify(WTF::Bind(&UserMediaClient::CurrentRequestCompleted,
                                     WrapWeakPersistent(this)));
    } else {
      CurrentRequestCompleted();
    }
  }
}

void UserMediaClient::CurrentRequestCompleted() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  is_processing_request_ = false;
  if (!pending_request_infos_.empty()) {
    frame_->GetTaskRunner(blink::TaskType::kInternalMedia)
        ->PostTask(FROM_HERE,
                   WTF::Bind(&UserMediaClient::MaybeProcessNextRequestInfo,
                             WrapWeakPersistent(this)));
  }
}

void UserMediaClient::CancelUserMediaRequest(
    UserMediaRequest* user_media_request) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  {
    // TODO(guidou): Remove this conditional logging. https://crbug.com/764293
    UserMediaRequest* request = user_media_processor_->CurrentRequest();
    if (request == user_media_request) {
      blink::WebRtcLogMessage(
          base::StringPrintf("UMCI::CancelUserMediaRequest. request_id=%d",
                             request->request_id()));
    }
  }

  bool did_remove_request = false;
  if (user_media_processor_->DeleteUserMediaRequest(user_media_request)) {
    did_remove_request = true;
  } else {
    for (auto it = pending_request_infos_.begin();
         it != pending_request_infos_.end(); ++it) {
      if ((*it)->IsUserMedia() &&
          (*it)->user_media_request() == user_media_request) {
        pending_request_infos_.erase(it);
        did_remove_request = true;
        break;
      }
    }
  }

  if (did_remove_request) {
    // We can't abort the stream generation process.
    // Instead, erase the request. Once the stream is generated we will stop the
    // stream if the request does not exist.
    LogUserMediaRequestWithNoResult(
        blink::MEDIA_STREAM_REQUEST_EXPLICITLY_CANCELLED);
  }
}

void UserMediaClient::DeleteAllUserMediaRequests() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (frame_)
    frame_->SetIsCapturingMediaCallback(LocalFrame::IsCapturingMediaCallback());
  user_media_processor_->StopAllProcessing();
  is_processing_request_ = false;
  pending_request_infos_.clear();
}

void UserMediaClient::ContextDestroyed() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  // Cancel all outstanding UserMediaRequests.
  DeleteAllUserMediaRequests();
}

void UserMediaClient::Trace(Visitor* visitor) {
  visitor->Trace(frame_);
  visitor->Trace(user_media_processor_);
  visitor->Trace(apply_constraints_processor_);
  visitor->Trace(pending_request_infos_);
}

void UserMediaClient::SetMediaDevicesDispatcherForTesting(
    mojo::PendingRemote<blink::mojom::blink::MediaDevicesDispatcherHost>
        media_devices_dispatcher) {
  media_devices_dispatcher_.Bind(std::move(media_devices_dispatcher));
}

blink::mojom::blink::MediaDevicesDispatcherHost*
UserMediaClient::GetMediaDevicesDispatcher() {
  if (!media_devices_dispatcher_) {
    frame_->GetBrowserInterfaceBroker().GetInterface(
        media_devices_dispatcher_.BindNewPipeAndPassReceiver());
  }

  return media_devices_dispatcher_.get();
}

}  // namespace blink