summaryrefslogtreecommitdiffstats
path: root/content/browser/media/capture/web_contents_audio_input_stream.cc
blob: 7dd34e861963c53eb928bdea819f0dd859532135 (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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright (c) 2013 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 "content/browser/media/capture/web_contents_audio_input_stream.h"

#include <string>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/thread_checker.h"
#include "content/browser/media/capture/audio_mirroring_manager.h"
#include "content/browser/media/capture/web_contents_tracker.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_media_capture_id.h"
#include "media/audio/virtual_audio_input_stream.h"
#include "media/audio/virtual_audio_output_stream.h"
#include "media/base/bind_to_current_loop.h"

namespace content {

class WebContentsAudioInputStream::Impl
    : public base::RefCountedThreadSafe<WebContentsAudioInputStream::Impl>,
      public AudioMirroringManager::MirroringDestination {
 public:
  // Takes ownership of |mixer_stream|.  The rest outlive this instance.
  Impl(int render_process_id, int main_render_frame_id,
       AudioMirroringManager* mirroring_manager,
       const scoped_refptr<WebContentsTracker>& tracker,
       media::VirtualAudioInputStream* mixer_stream);

  // Open underlying VirtualAudioInputStream and start tracker.
  bool Open();

  // Start the underlying VirtualAudioInputStream and instruct
  // AudioMirroringManager to begin a mirroring session.
  void Start(AudioInputCallback* callback);

  // Stop the underlying VirtualAudioInputStream and instruct
  // AudioMirroringManager to shutdown a mirroring session.
  void Stop();

  // Close the underlying VirtualAudioInputStream and stop the tracker.
  void Close();

  // Accessor to underlying VirtualAudioInputStream.
  media::VirtualAudioInputStream* mixer_stream() const {
    return mixer_stream_.get();
  }

 private:
  friend class base::RefCountedThreadSafe<WebContentsAudioInputStream::Impl>;

  typedef AudioMirroringManager::SourceFrameRef SourceFrameRef;

  enum State {
    CONSTRUCTED,
    OPENED,
    MIRRORING,
    CLOSED
  };

  ~Impl() override;

  // Notifies the consumer callback that the stream is now dead.
  void ReportError();

  // (Re-)Start/Stop mirroring by posting a call to AudioMirroringManager on the
  // IO BrowserThread.
  void StartMirroring();
  void StopMirroring();

  // Invoked on the UI thread to make sure WebContents muting is turned off for
  // successful audio capture.
  void UnmuteWebContentsAudio();

  // AudioMirroringManager::MirroringDestination implementation
  void QueryForMatches(const std::set<SourceFrameRef>& candidates,
                       const MatchesCallback& results_callback) override;
  void QueryForMatchesOnUIThread(const std::set<SourceFrameRef>& candidates,
                                 const MatchesCallback& results_callback);
  media::AudioOutputStream* AddInput(
      const media::AudioParameters& params) override;

  // Callback which is run when |stream| is closed.  Deletes |stream|.
  void ReleaseInput(media::VirtualAudioOutputStream* stream);

  // Called by WebContentsTracker when the target of the audio mirroring has
  // changed.
  void OnTargetChanged(bool had_target);

  // Injected dependencies.
  const int initial_render_process_id_;
  const int initial_main_render_frame_id_;
  AudioMirroringManager* const mirroring_manager_;
  const scoped_refptr<WebContentsTracker> tracker_;
  // The AudioInputStream implementation that handles the audio conversion and
  // mixing details.
  const scoped_ptr<media::VirtualAudioInputStream> mixer_stream_;

  State state_;

  // Set to true if |tracker_| reports a NULL target, which indicates the target
  // is permanently lost.
  bool is_target_lost_;

  // Current callback used to consume the resulting mixed audio data.
  AudioInputCallback* callback_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(Impl);
};

WebContentsAudioInputStream::Impl::Impl(
    int render_process_id, int main_render_frame_id,
    AudioMirroringManager* mirroring_manager,
    const scoped_refptr<WebContentsTracker>& tracker,
    media::VirtualAudioInputStream* mixer_stream)
    : initial_render_process_id_(render_process_id),
      initial_main_render_frame_id_(main_render_frame_id),
      mirroring_manager_(mirroring_manager),
      tracker_(tracker),
      mixer_stream_(mixer_stream),
      state_(CONSTRUCTED),
      is_target_lost_(false),
      callback_(NULL) {
  DCHECK(mirroring_manager_);
  DCHECK(tracker_.get());
  DCHECK(mixer_stream_.get());

  // WAIS::Impl can be constructed on any thread, but will DCHECK that all
  // its methods from here on are called from the same thread.
  thread_checker_.DetachFromThread();
}

WebContentsAudioInputStream::Impl::~Impl() {
  DCHECK(state_ == CONSTRUCTED || state_ == CLOSED);
}

bool WebContentsAudioInputStream::Impl::Open() {
  DCHECK(thread_checker_.CalledOnValidThread());

  DCHECK_EQ(CONSTRUCTED, state_) << "Illegal to Open more than once.";

  if (!mixer_stream_->Open())
    return false;

  state_ = OPENED;

  tracker_->Start(
      initial_render_process_id_, initial_main_render_frame_id_,
      base::Bind(&Impl::OnTargetChanged, this));

  return true;
}

void WebContentsAudioInputStream::Impl::Start(AudioInputCallback* callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(callback);

  if (state_ != OPENED)
    return;

  callback_ = callback;
  if (is_target_lost_) {
    ReportError();
    callback_ = NULL;
    return;
  }

  state_ = MIRRORING;
  mixer_stream_->Start(callback);

  StartMirroring();

  // WebContents audio muting is implemented as audio capture to nowhere.
  // Unmuting will stop that audio capture, allowing AudioMirroringManager to
  // divert audio capture to here.
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&Impl::UnmuteWebContentsAudio, this));
}

void WebContentsAudioInputStream::Impl::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (state_ != MIRRORING)
    return;

  state_ = OPENED;

  mixer_stream_->Stop();
  callback_ = NULL;

  StopMirroring();
}

void WebContentsAudioInputStream::Impl::Close() {
  DCHECK(thread_checker_.CalledOnValidThread());

  Stop();

  if (state_ == OPENED) {
    state_ = CONSTRUCTED;
    tracker_->Stop();
    mixer_stream_->Close();
  }

  DCHECK_EQ(CONSTRUCTED, state_);
  state_ = CLOSED;
}

void WebContentsAudioInputStream::Impl::ReportError() {
  DCHECK(thread_checker_.CalledOnValidThread());

  // TODO(miu): Need clean-up of AudioInputCallback interface in a future
  // change, since its only implementation ignores the first argument entirely
  callback_->OnError(NULL);
}

void WebContentsAudioInputStream::Impl::StartMirroring() {
  DCHECK(thread_checker_.CalledOnValidThread());

  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&AudioMirroringManager::StartMirroring,
                                     base::Unretained(mirroring_manager_),
                                     base::RetainedRef(this)));
}

void WebContentsAudioInputStream::Impl::StopMirroring() {
  DCHECK(thread_checker_.CalledOnValidThread());

  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&AudioMirroringManager::StopMirroring,
                                     base::Unretained(mirroring_manager_),
                                     base::RetainedRef(this)));
}

void WebContentsAudioInputStream::Impl::UnmuteWebContentsAudio() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  WebContents* const contents = tracker_->web_contents();
  if (contents)
    contents->SetAudioMuted(false);
}

void WebContentsAudioInputStream::Impl::QueryForMatches(
    const std::set<SourceFrameRef>& candidates,
    const MatchesCallback& results_callback) {
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&Impl::QueryForMatchesOnUIThread,
                 this,
                 candidates,
                 media::BindToCurrentLoop(results_callback)));
}

void WebContentsAudioInputStream::Impl::QueryForMatchesOnUIThread(
    const std::set<SourceFrameRef>& candidates,
    const MatchesCallback& results_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  std::set<SourceFrameRef> matches;
  WebContents* const contents = tracker_->web_contents();
  if (contents) {
    // Add each ID to |matches| if it maps to a RenderFrameHost that maps to the
    // currently-tracked WebContents.
    for (std::set<SourceFrameRef>::const_iterator i = candidates.begin();
         i != candidates.end(); ++i) {
      WebContents* const contents_containing_frame =
          WebContents::FromRenderFrameHost(
              RenderFrameHost::FromID(i->first, i->second));
      if (contents_containing_frame == contents)
        matches.insert(*i);
    }
  }

  results_callback.Run(matches);
}

media::AudioOutputStream* WebContentsAudioInputStream::Impl::AddInput(
    const media::AudioParameters& params) {
  // Note: The closure created here holds a reference to "this," which will
  // guarantee the VirtualAudioInputStream (mixer_stream_) outlives the
  // VirtualAudioOutputStream.
  return new media::VirtualAudioOutputStream(
      params,
      mixer_stream_.get(),
      base::Bind(&Impl::ReleaseInput, this));
}

void WebContentsAudioInputStream::Impl::ReleaseInput(
    media::VirtualAudioOutputStream* stream) {
  delete stream;
}

void WebContentsAudioInputStream::Impl::OnTargetChanged(bool had_target) {
  DCHECK(thread_checker_.CalledOnValidThread());

  is_target_lost_ = !had_target;

  if (state_ == MIRRORING) {
    if (is_target_lost_) {
      ReportError();
      Stop();
    } else {
      StartMirroring();
    }
  }
}

// static
WebContentsAudioInputStream* WebContentsAudioInputStream::Create(
    const std::string& device_id,
    const media::AudioParameters& params,
    const scoped_refptr<base::SingleThreadTaskRunner>& worker_task_runner,
    AudioMirroringManager* audio_mirroring_manager) {
  int render_process_id;
  int main_render_frame_id;
  if (!WebContentsMediaCaptureId::ExtractTabCaptureTarget(
          device_id, &render_process_id, &main_render_frame_id)) {
    return NULL;
  }

  return new WebContentsAudioInputStream(
      render_process_id, main_render_frame_id,
      audio_mirroring_manager,
      new WebContentsTracker(false),
      new media::VirtualAudioInputStream(
          params, worker_task_runner,
          media::VirtualAudioInputStream::AfterCloseCallback()));
}

WebContentsAudioInputStream::WebContentsAudioInputStream(
    int render_process_id, int main_render_frame_id,
    AudioMirroringManager* mirroring_manager,
    const scoped_refptr<WebContentsTracker>& tracker,
    media::VirtualAudioInputStream* mixer_stream)
    : impl_(new Impl(render_process_id, main_render_frame_id,
                     mirroring_manager, tracker, mixer_stream)) {}

WebContentsAudioInputStream::~WebContentsAudioInputStream() {}

bool WebContentsAudioInputStream::Open() {
  return impl_->Open();
}

void WebContentsAudioInputStream::Start(AudioInputCallback* callback) {
  impl_->Start(callback);
}

void WebContentsAudioInputStream::Stop() {
  impl_->Stop();
}

void WebContentsAudioInputStream::Close() {
  impl_->Close();
  delete this;
}

double WebContentsAudioInputStream::GetMaxVolume() {
  return impl_->mixer_stream()->GetMaxVolume();
}

void WebContentsAudioInputStream::SetVolume(double volume) {
  impl_->mixer_stream()->SetVolume(volume);
}

double WebContentsAudioInputStream::GetVolume() {
  return impl_->mixer_stream()->GetVolume();
}

bool WebContentsAudioInputStream::SetAutomaticGainControl(bool enabled) {
  return impl_->mixer_stream()->SetAutomaticGainControl(enabled);
}

bool WebContentsAudioInputStream::GetAutomaticGainControl() {
  return impl_->mixer_stream()->GetAutomaticGainControl();
}

bool WebContentsAudioInputStream::IsMuted() {
  return false;
}

}  // namespace content