Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / renderer / media / rtc_dtmf_sender_handler.cc
blob65b60b8d3f8112a2b58771f6dcd4df7ebbabc62a
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/media/rtc_dtmf_sender_handler.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/thread_checker.h"
16 using webrtc::DtmfSenderInterface;
18 namespace content {
20 class RtcDtmfSenderHandler::Observer :
21 public base::RefCountedThreadSafe<Observer>,
22 public webrtc::DtmfSenderObserverInterface {
23 public:
24 explicit Observer(const base::WeakPtr<RtcDtmfSenderHandler>& handler)
25 : main_thread_(base::MessageLoopProxy::current()), handler_(handler) {}
27 private:
28 friend class base::RefCountedThreadSafe<Observer>;
30 ~Observer() override {}
32 void OnToneChange(const std::string& tone) override {
33 main_thread_->PostTask(FROM_HERE,
34 base::Bind(&RtcDtmfSenderHandler::Observer::OnToneChangeOnMainThread,
35 this, tone));
38 void OnToneChangeOnMainThread(const std::string& tone) {
39 DCHECK(thread_checker_.CalledOnValidThread());
40 if (handler_)
41 handler_->OnToneChange(tone);
44 base::ThreadChecker thread_checker_;
45 const scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
46 base::WeakPtr<RtcDtmfSenderHandler> handler_;
49 RtcDtmfSenderHandler::RtcDtmfSenderHandler(DtmfSenderInterface* dtmf_sender)
50 : dtmf_sender_(dtmf_sender),
51 webkit_client_(NULL),
52 weak_factory_(this) {
53 DVLOG(1) << "::ctor";
54 observer_ = new Observer(weak_factory_.GetWeakPtr());
55 dtmf_sender_->RegisterObserver(observer_.get());
58 RtcDtmfSenderHandler::~RtcDtmfSenderHandler() {
59 DVLOG(1) << "::dtor";
60 dtmf_sender_->UnregisterObserver();
61 // Release |observer| before |weak_factory_| is destroyed.
62 observer_ = NULL;
65 void RtcDtmfSenderHandler::setClient(
66 blink::WebRTCDTMFSenderHandlerClient* client) {
67 webkit_client_ = client;
70 blink::WebString RtcDtmfSenderHandler::currentToneBuffer() {
71 return base::UTF8ToUTF16(dtmf_sender_->tones());
74 bool RtcDtmfSenderHandler::canInsertDTMF() {
75 return dtmf_sender_->CanInsertDtmf();
78 bool RtcDtmfSenderHandler::insertDTMF(const blink::WebString& tones,
79 long duration,
80 long interToneGap) {
81 std::string utf8_tones = base::UTF16ToUTF8(tones);
82 return dtmf_sender_->InsertDtmf(utf8_tones, static_cast<int>(duration),
83 static_cast<int>(interToneGap));
86 void RtcDtmfSenderHandler::OnToneChange(const std::string& tone) {
87 if (!webkit_client_) {
88 LOG(ERROR) << "WebRTCDTMFSenderHandlerClient not set.";
89 return;
91 webkit_client_->didPlayTone(base::UTF8ToUTF16(tone));
94 } // namespace content