summaryrefslogtreecommitdiffstats
path: root/components/devtools_bridge/session_dependency_factory.cc
blob: 567771f2df4b46dfe3ef7009e5493abb1307db7c (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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Copyright 2014 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 "components/devtools_bridge/session_dependency_factory.h"

#include "base/bind.h"
#include "base/location.h"
#include "base/task_runner.h"
#include "base/threading/thread.h"
#include "components/devtools_bridge/abstract_data_channel.h"
#include "components/devtools_bridge/abstract_peer_connection.h"
#include "components/devtools_bridge/rtc_configuration.h"
#include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h"
#include "third_party/libjingle/source/talk/app/webrtc/peerconnectioninterface.h"
#include "third_party/webrtc/base/bind.h"
#include "third_party/webrtc/base/messagehandler.h"
#include "third_party/webrtc/base/messagequeue.h"
#include "third_party/webrtc/base/ssladapter.h"
#include "third_party/webrtc/base/thread.h"

namespace devtools_bridge {

class RTCConfiguration::Impl
    : public RTCConfiguration,
      public webrtc::PeerConnectionInterface::RTCConfiguration {
 public:
  void AddIceServer(const std::string& uri,
                    const std::string& username,
                    const std::string& credential) override {
    webrtc::PeerConnectionInterface::IceServer server;
    server.uri = uri;
    server.username = username;
    server.password = credential;
    servers.push_back(server);
  }

  const Impl& impl() const override {
    return *this;
  }

 private:
  webrtc::PeerConnectionInterface::RTCConfiguration base_;
};

namespace {

template <typename T>
void CheckedRelease(rtc::scoped_refptr<T>* ptr) {
  CHECK_EQ(0, ptr->release()->Release());
}

class MediaConstraints
    : public webrtc::MediaConstraintsInterface {
 public:
  ~MediaConstraints() override {}

  const Constraints& GetMandatory() const override { return mandatory_; }

  const Constraints& GetOptional() const override { return optional_; }

  void AddMandatory(const std::string& key, const std::string& value) {
    mandatory_.push_back(Constraint(key, value));
  }

 private:
  Constraints mandatory_;
  Constraints optional_;
};

/**
 * Posts tasks on signaling thread. If stopped (when SesseionDependencyFactry
 * is destroying) ignores posted tasks.
 */
class SignalingThreadTaskRunner : public base::TaskRunner,
                                  private rtc::MessageHandler {
 public:
  explicit SignalingThreadTaskRunner(rtc::Thread* thread) : thread_(thread) {}

  bool PostDelayedTask(const tracked_objects::Location& from_here,
                       const base::Closure& task,
                       base::TimeDelta delay) override {
    DCHECK(delay.ToInternalValue() == 0);

    rtc::CritScope scope(&critical_section_);

    if (thread_)
      thread_->Send(this, 0, new Task(task));

    return true;
  }

  bool RunsTasksOnCurrentThread() const override {
    rtc::CritScope scope(&critical_section_);

    return thread_ != NULL && thread_->IsCurrent();
  }

  void Stop() {
    rtc::CritScope scope(&critical_section_);
    thread_ = NULL;
  }

 private:
  typedef rtc::TypedMessageData<base::Closure> Task;

  ~SignalingThreadTaskRunner() override {}

  void OnMessage(rtc::Message* msg) override {
    static_cast<Task*>(msg->pdata)->data().Run();
  }

  mutable rtc::CriticalSection critical_section_;
  rtc::Thread* thread_;  // Guarded by |critical_section_|.
};

class DataChannelObserverImpl : public webrtc::DataChannelObserver {
 public:
  DataChannelObserverImpl(
      webrtc::DataChannelInterface* data_channel,
      scoped_ptr<AbstractDataChannel::Observer> observer)
      : data_channel_(data_channel),
        observer_(observer.Pass()) {
  }

  void InitState() {
    open_ = data_channel_->state() == webrtc::DataChannelInterface::kOpen;
  }

  void OnStateChange() override {
    bool open = data_channel_->state() == webrtc::DataChannelInterface::kOpen;

    if (open == open_) return;

    open_ = open;
    if (open) {
      observer_->OnOpen();
    } else {
      observer_->OnClose();
    }
  }

  void OnMessage(const webrtc::DataBuffer& buffer) override {
    observer_->OnMessage(buffer.data.data(), buffer.size());
  }

 private:
  webrtc::DataChannelInterface* const data_channel_;
  scoped_ptr<AbstractDataChannel::Observer> const observer_;
  bool open_;
};

/**
 * Thread-safe view on AbstractDataChannel.
 */
class DataChannelProxyImpl : public AbstractDataChannel::Proxy {
 public:
  DataChannelProxyImpl(
      SessionDependencyFactory* factory,
      rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
      : data_channel_(data_channel),
        signaling_thread_task_runner_(
            factory->signaling_thread_task_runner()) {
  }

  void StopOnSignalingThread() {
    data_channel_ = NULL;
  }

  void SendBinaryMessage(const void* data, size_t length) override {
    auto buffer = make_scoped_ptr(new webrtc::DataBuffer(rtc::Buffer(), true));
    buffer->data.SetData(data, length);

    signaling_thread_task_runner_->PostTask(
        FROM_HERE, base::Bind(
            &DataChannelProxyImpl::SendMessageOnSignalingThread,
            this,
            base::Passed(&buffer)));
  }

  void Close() override {
    signaling_thread_task_runner_->PostTask(
        FROM_HERE, base::Bind(&DataChannelProxyImpl::CloseOnSignalingThread,
                              this));
  }

 private:

  ~DataChannelProxyImpl() override {}

  void SendMessageOnSignalingThread(scoped_ptr<webrtc::DataBuffer> message) {
    if (data_channel_ != NULL)
      data_channel_->Send(*message);
  }

  void CloseOnSignalingThread() {
    if (data_channel_ != NULL)
      data_channel_->Close();
  }

  // Accessed on signaling thread.
  rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel_;

  const scoped_refptr<base::TaskRunner> signaling_thread_task_runner_;
};

class DataChannelImpl : public AbstractDataChannel {
 public:
  DataChannelImpl(
      SessionDependencyFactory* factory,
      rtc::Thread* const signaling_thread,
      rtc::scoped_refptr<webrtc::DataChannelInterface> impl)
      : factory_(factory),
        signaling_thread_(signaling_thread),
        impl_(impl) {
  }

  ~DataChannelImpl() override {
    if (proxy_.get()) {
      signaling_thread_->Invoke<void>(rtc::Bind(
          &DataChannelProxyImpl::StopOnSignalingThread, proxy_.get()));
    }
  }

  void RegisterObserver(scoped_ptr<Observer> observer) override {
    observer_.reset(new DataChannelObserverImpl(impl_.get(), observer.Pass()));
    signaling_thread_->Invoke<void>(rtc::Bind(
        &DataChannelImpl::RegisterObserverOnSignalingThread, this));
  }

  void UnregisterObserver() override {
    DCHECK(observer_.get() != NULL);
    impl_->UnregisterObserver();
    observer_.reset();
  }

  void SendBinaryMessage(void* data, size_t length) override {
    SendMessage(data, length, true);
  }

  void SendTextMessage(void* data, size_t length) override {
    SendMessage(data, length, false);
  }

  void SendMessage(void* data, size_t length, bool is_binary) {
    impl_->Send(webrtc::DataBuffer(rtc::Buffer(data, length), is_binary));
  }

  void Close() override {
    impl_->Close();
  }

  scoped_refptr<Proxy> proxy() override {
    if (!proxy_.get())
      proxy_ = new DataChannelProxyImpl(factory_, impl_);
    return proxy_;
  }

 private:
  void RegisterObserverOnSignalingThread() {
    // State initialization and observer registration happen atomically
    // if done on the signaling thread (see rtc::Thread::Send).
    observer_->InitState();
    impl_->RegisterObserver(observer_.get());
  }

  SessionDependencyFactory* const factory_;
  scoped_refptr<DataChannelProxyImpl> proxy_;
  rtc::Thread* const signaling_thread_;
  scoped_ptr<DataChannelObserverImpl> observer_;
  const rtc::scoped_refptr<webrtc::DataChannelInterface> impl_;
};

class PeerConnectionObserverImpl
    : public webrtc::PeerConnectionObserver {
 public:
  PeerConnectionObserverImpl(AbstractPeerConnection::Delegate* delegate)
      : delegate_(delegate),
        connected_(false) {
  }

  void OnAddStream(webrtc::MediaStreamInterface* stream) override {}

  void OnRemoveStream(webrtc::MediaStreamInterface* stream) override {}

  void OnDataChannel(webrtc::DataChannelInterface* data_channel) override {}

  void OnRenegotiationNeeded() override {}

  void OnSignalingChange(
      webrtc::PeerConnectionInterface::SignalingState new_state) override {}

  void OnIceConnectionChange(
      webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
    bool connected =
        new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected ||
        new_state == webrtc::PeerConnectionInterface::kIceConnectionCompleted;

    if (connected != connected_) {
      connected_ = connected;
      delegate_->OnIceConnectionChange(connected_);
    }
  }

  void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
    std::string sdp;
    candidate->ToString(&sdp);

    delegate_->OnIceCandidate(
        candidate->sdp_mid(), candidate->sdp_mline_index(), sdp);
  }

 private:
  AbstractPeerConnection::Delegate* const delegate_;
  bool connected_;
};

/**
 * Helper object which may outlive PeerConnectionImpl. Provides access
 * to the connection and the delegate to operaion callback objects
 * in a safe way. Always accessible on the signaling thread.
 */
class PeerConnectionHolder : public rtc::RefCountInterface {
 public:
  PeerConnectionHolder(
      rtc::Thread* signaling_thread,
      webrtc::PeerConnectionInterface* connection,
      AbstractPeerConnection::Delegate* delegate)
      : signaling_thread_(signaling_thread),
        connection_(connection),
        delegate_(delegate),
        disposed_(false) {
  }

  ~PeerConnectionHolder() override { DCHECK(disposed_); }

  void Dispose() {
    DCHECK(!IsDisposed());
    disposed_ = true;
  }

  webrtc::PeerConnectionInterface* connection() {
    DCHECK(!IsDisposed());
    return connection_;
  }

  AbstractPeerConnection::Delegate* delegate() {
    DCHECK(!IsDisposed());
    return delegate_;
  }

  bool IsDisposed() {
    DCHECK(signaling_thread_->IsCurrent());
    return disposed_;
  }

 private:
  rtc::Thread* const signaling_thread_;
  webrtc::PeerConnectionInterface* const connection_;
  AbstractPeerConnection::Delegate* const delegate_;
  bool disposed_;
};

class CreateAndSetHandler
    : public webrtc::CreateSessionDescriptionObserver,
      public webrtc::SetSessionDescriptionObserver {
 public:
  explicit CreateAndSetHandler(
      rtc::scoped_refptr<PeerConnectionHolder> holder)
      : holder_(holder) {
  }

  void OnSuccess(webrtc::SessionDescriptionInterface* desc) override {
    if (holder_->IsDisposed()) return;

    type_ = desc->type();
    if (desc->ToString(&description_)) {
      holder_->connection()->SetLocalDescription(this, desc);
    } else {
      OnFailure("Can't serialize session description");
    }
  }

  void OnSuccess() override {
    if (holder_->IsDisposed()) return;

    if (type_ == webrtc::SessionDescriptionInterface::kOffer) {
      holder_->delegate()->OnLocalOfferCreatedAndSetSet(description_);
    } else {
      DCHECK_EQ(webrtc::SessionDescriptionInterface::kAnswer, type_);

      holder_->delegate()->OnLocalAnswerCreatedAndSetSet(description_);
    }
  }

  void OnFailure(const std::string& error) override {
    if (holder_->IsDisposed()) return;

    holder_->delegate()->OnFailure(error);
  }

 private:
  const rtc::scoped_refptr<PeerConnectionHolder> holder_;
  std::string type_;
  std::string description_;
};

class SetRemoteDescriptionHandler
   : public webrtc::SetSessionDescriptionObserver {
 public:
  SetRemoteDescriptionHandler(
      rtc::scoped_refptr<PeerConnectionHolder> holder)
      : holder_(holder) {
  }

  void OnSuccess() override {
    if (holder_->IsDisposed()) return;

    holder_->delegate()->OnRemoteDescriptionSet();
  }

  void OnFailure(const std::string& error) override {
    if (holder_->IsDisposed()) return;

    holder_->delegate()->OnFailure(error);
  }

 private:
  const rtc::scoped_refptr<PeerConnectionHolder> holder_;
};

class PeerConnectionImpl : public AbstractPeerConnection {
 public:
  PeerConnectionImpl(
      SessionDependencyFactory* const factory,
      rtc::Thread* signaling_thread,
      rtc::scoped_refptr<webrtc::PeerConnectionInterface> connection,
      scoped_ptr<PeerConnectionObserverImpl> observer,
      scoped_ptr<AbstractPeerConnection::Delegate> delegate)
      : factory_(factory),
        holder_(new rtc::RefCountedObject<PeerConnectionHolder>(
            signaling_thread, connection.get(), delegate.get())),
        signaling_thread_(signaling_thread),
        connection_(connection),
        observer_(observer.Pass()),
        delegate_(delegate.Pass()) {
  }

  ~PeerConnectionImpl() override {
    signaling_thread_->Invoke<void>(rtc::Bind(
        &PeerConnectionImpl::DisposeOnSignalingThread, this));
  }

  void CreateAndSetLocalOffer() override {
    connection_->CreateOffer(MakeCreateAndSetHandler(), NULL);
  }

  void CreateAndSetLocalAnswer() override {
    connection_->CreateAnswer(MakeCreateAndSetHandler(), NULL);
  }

  void SetRemoteOffer(const std::string& description) override {
    SetRemoteDescription(
        webrtc::SessionDescriptionInterface::kOffer, description);
  }

  void SetRemoteAnswer(const std::string& description) override {
    SetRemoteDescription(
        webrtc::SessionDescriptionInterface::kAnswer, description);
  }

  void SetRemoteDescription(
      const std::string& type, const std::string& description) {
    webrtc::SdpParseError error;
    scoped_ptr<webrtc::SessionDescriptionInterface> value(
        webrtc::CreateSessionDescription(type, description, &error));
    if (value == NULL) {
      OnParseError(error);
      return;
    }
    // Takes ownership on |value|.
    connection_->SetRemoteDescription(
        new rtc::RefCountedObject<SetRemoteDescriptionHandler>(holder_),
        value.release());
  }

  void AddIceCandidate(const std::string& sdp_mid,
                       int sdp_mline_index,
                       const std::string& sdp) override {
    webrtc::SdpParseError error;
    auto candidate = webrtc::CreateIceCandidate(
        sdp_mid, sdp_mline_index, sdp, &error);
    if (candidate == NULL) {
      OnParseError(error);
      return;
    }
    // Doesn't takes ownership.
    connection_->AddIceCandidate(candidate);
    delete candidate;
  }

  scoped_ptr<AbstractDataChannel> CreateDataChannel(int channelId) override {
    webrtc::DataChannelInit init;
    init.ordered = true;
    init.negotiated = true;
    init.id = channelId;

    return make_scoped_ptr(new DataChannelImpl(
        factory_,
        signaling_thread_,
        connection_->CreateDataChannel("", &init)));
  }

 private:
  webrtc::CreateSessionDescriptionObserver* MakeCreateAndSetHandler() {
    return new rtc::RefCountedObject<CreateAndSetHandler>(holder_);
  }

  void DisposeOnSignalingThread() {
    DCHECK(signaling_thread_->IsCurrent());

    CheckedRelease(&connection_);
    holder_->Dispose();
  }

  void OnParseError(const webrtc::SdpParseError& error) {
    // TODO(serya): Send on signaling thread.
  }

  SessionDependencyFactory* const factory_;
  const rtc::scoped_refptr<PeerConnectionHolder> holder_;
  rtc::Thread* const signaling_thread_;
  rtc::scoped_refptr<webrtc::PeerConnectionInterface> connection_;
  const scoped_ptr<PeerConnectionObserverImpl> observer_;
  const scoped_ptr<AbstractPeerConnection::Delegate> delegate_;
};

class SessionDependencyFactoryImpl : public SessionDependencyFactory {
 public:
  SessionDependencyFactoryImpl(
      const base::Closure& cleanup_on_signaling_thread)
      : cleanup_on_signaling_thread_(cleanup_on_signaling_thread) {
    signaling_thread_.SetName("signaling_thread", NULL);
    signaling_thread_.Start();
    worker_thread_.SetName("worker_thread", NULL);
    worker_thread_.Start();

    factory_ = webrtc::CreatePeerConnectionFactory(
        &worker_thread_, &signaling_thread_, NULL, NULL, NULL);
  }

  ~SessionDependencyFactoryImpl() override {
    if (signaling_thread_task_runner_.get())
      signaling_thread_task_runner_->Stop();

    signaling_thread_.Invoke<void>(rtc::Bind(
        &SessionDependencyFactoryImpl::DisposeOnSignalingThread, this));
  }

  scoped_ptr<AbstractPeerConnection> CreatePeerConnection(
      scoped_ptr<RTCConfiguration> config,
      scoped_ptr<AbstractPeerConnection::Delegate> delegate) override {
    auto observer = make_scoped_ptr(
        new PeerConnectionObserverImpl(delegate.get()));

    MediaConstraints constraints;
    constraints.AddMandatory(
        MediaConstraints::kEnableDtlsSrtp, MediaConstraints::kValueTrue);

    auto connection = factory_->CreatePeerConnection(
        config->impl(), &constraints, NULL, NULL, observer.get());

    return make_scoped_ptr(new PeerConnectionImpl(
        this, &signaling_thread_, connection, observer.Pass(),
        delegate.Pass()));
  }

  scoped_refptr<base::TaskRunner> signaling_thread_task_runner() override {
    if (!signaling_thread_task_runner_.get()) {
      signaling_thread_task_runner_ =
          new SignalingThreadTaskRunner(&signaling_thread_);
    }
    return signaling_thread_task_runner_;
  }

  scoped_refptr<base::TaskRunner> io_thread_task_runner() override {
    if (!io_thread_.get()) {
      io_thread_.reset(new base::Thread("devtools bridge IO thread"));
      base::Thread::Options options;
      options.message_loop_type = base::MessageLoop::TYPE_IO;
      CHECK(io_thread_->StartWithOptions(options));
    }
    return io_thread_->task_runner();
  }

 private:
  void DisposeOnSignalingThread() {
    DCHECK(signaling_thread_.IsCurrent());
    CheckedRelease(&factory_);
    if (!cleanup_on_signaling_thread_.is_null())
      cleanup_on_signaling_thread_.Run();
  }

  scoped_ptr<base::Thread> io_thread_;
  scoped_refptr<SignalingThreadTaskRunner> signaling_thread_task_runner_;
  base::Closure cleanup_on_signaling_thread_;
  rtc::Thread signaling_thread_;
  rtc::Thread worker_thread_;
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory_;
};

} // namespace

// RTCCOnfiguration

// static
scoped_ptr<RTCConfiguration> RTCConfiguration::CreateInstance() {
  return make_scoped_ptr(new RTCConfiguration::Impl());
}

// SessionDependencyFactory

// static
bool SessionDependencyFactory::InitializeSSL() {
  return rtc::InitializeSSL();
}

// static
bool SessionDependencyFactory::CleanupSSL() {
  return rtc::CleanupSSL();
}

// static
scoped_ptr<SessionDependencyFactory> SessionDependencyFactory::CreateInstance(
    const base::Closure& cleanup_on_signaling_thread) {
  return make_scoped_ptr(new SessionDependencyFactoryImpl(
      cleanup_on_signaling_thread));
}

}  // namespace devtools_bridge