Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / media / router / media_router_mojo_impl.cc
bloba4546fdc464fa24c83929bcd4ec690c31846d50c
1 // Copyright 2015 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 "chrome/browser/media/router/media_router_mojo_impl.h"
7 #include "base/bind.h"
8 #include "base/guid.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_vector.h"
11 #include "base/observer_list.h"
12 #include "base/strings/stringprintf.h"
13 #include "chrome/browser/media/router/issues_observer.h"
14 #include "chrome/browser/media/router/media_router_factory.h"
15 #include "chrome/browser/media/router/media_router_type_converters.h"
16 #include "chrome/browser/media/router/media_routes_observer.h"
17 #include "chrome/browser/media/router/media_sinks_observer.h"
18 #include "chrome/browser/media/router/presentation_session_messages_observer.h"
19 #include "extensions/browser/process_manager.h"
21 #define DVLOG_WITH_INSTANCE(level) \
22 DVLOG(level) << "MR #" << instance_id_ << ": "
24 #define DLOG_WITH_INSTANCE(level) DLOG(level) << "MR #" << instance_id_ << ": "
26 namespace media_router {
27 namespace {
29 // Converts the callback result of calling Mojo CreateRoute()/JoinRoute()
30 // into a local callback.
31 void RouteResponseReceived(
32 const std::string& presentation_id,
33 const std::vector<MediaRouteResponseCallback>& callbacks,
34 interfaces::MediaRoutePtr media_route,
35 const mojo::String& error_text) {
36 scoped_ptr<MediaRoute> route;
37 std::string actual_presentation_id;
38 std::string error;
39 if (media_route.is_null()) {
40 // An error occurred.
41 DCHECK(!error_text.is_null());
42 error = !error_text.get().empty() ? error_text.get() : "Unknown error.";
43 } else {
44 route = media_route.To<scoped_ptr<MediaRoute>>();
45 actual_presentation_id = presentation_id;
48 for (const MediaRouteResponseCallback& callback : callbacks)
49 callback.Run(route.get(), actual_presentation_id, error);
52 // TODO(imcheng): We should handle failure in this case. One way is to invoke
53 // all pending requests with failure. (crbug.com/490787)
54 void EventPageWakeComplete(bool success) {
55 if (!success)
56 LOG(ERROR) << "An error encountered while waking the event page.";
59 scoped_ptr<content::PresentationSessionMessage>
60 ConvertToPresentationSessionMessage(interfaces::RouteMessagePtr input) {
61 DCHECK(!input.is_null());
62 scoped_ptr<content::PresentationSessionMessage> output;
63 switch (input->type) {
64 case interfaces::RouteMessage::Type::TYPE_TEXT: {
65 DCHECK(!input->message.is_null());
66 DCHECK(input->data.is_null());
67 output.reset(new content::PresentationSessionMessage(
68 content::PresentationMessageType::TEXT));
69 input->message.Swap(&output->message);
70 return output.Pass();
72 case interfaces::RouteMessage::Type::TYPE_BINARY: {
73 DCHECK(!input->data.is_null());
74 DCHECK(input->message.is_null());
75 output.reset(new content::PresentationSessionMessage(
76 content::PresentationMessageType::ARRAY_BUFFER));
77 output->data.reset(new std::vector<uint8_t>);
78 input->data.Swap(output->data.get());
79 return output.Pass();
83 NOTREACHED() << "Invalid route message type " << input->type;
84 return output.Pass();
87 } // namespace
89 MediaRouterMojoImpl::MediaRouterMojoImpl(
90 extensions::EventPageTracker* event_page_tracker)
91 : event_page_tracker_(event_page_tracker),
92 instance_id_(base::GenerateGUID()) {
93 DCHECK(event_page_tracker_);
96 MediaRouterMojoImpl::~MediaRouterMojoImpl() {
97 DCHECK(thread_checker_.CalledOnValidThread());
100 // static
101 void MediaRouterMojoImpl::BindToRequest(
102 const std::string& extension_id,
103 content::BrowserContext* context,
104 mojo::InterfaceRequest<interfaces::MediaRouter> request) {
105 MediaRouterMojoImpl* impl = static_cast<MediaRouterMojoImpl*>(
106 MediaRouterFactory::GetApiForBrowserContext(context));
107 DCHECK(impl);
109 impl->BindToMojoRequest(request.Pass(), extension_id);
112 void MediaRouterMojoImpl::BindToMojoRequest(
113 mojo::InterfaceRequest<interfaces::MediaRouter> request,
114 const std::string& extension_id) {
115 DCHECK(thread_checker_.CalledOnValidThread());
117 binding_.reset(
118 new mojo::Binding<interfaces::MediaRouter>(this, request.Pass()));
119 binding_->set_connection_error_handler(base::Bind(
120 &MediaRouterMojoImpl::OnConnectionError, base::Unretained(this)));
122 media_route_provider_extension_id_ = extension_id;
125 // TODO(imcheng): If this occurs while there are pending requests, we should
126 // probably invoke them with failure. (crbug.com/490787)
127 void MediaRouterMojoImpl::OnConnectionError() {
128 DCHECK(thread_checker_.CalledOnValidThread());
130 media_route_provider_.reset();
131 binding_.reset();
134 void MediaRouterMojoImpl::RegisterMediaRouteProvider(
135 interfaces::MediaRouteProviderPtr media_route_provider_ptr,
136 const interfaces::MediaRouter::RegisterMediaRouteProviderCallback&
137 callback) {
138 DCHECK(thread_checker_.CalledOnValidThread());
140 media_route_provider_ = media_route_provider_ptr.Pass();
141 media_route_provider_.set_connection_error_handler(base::Bind(
142 &MediaRouterMojoImpl::OnConnectionError, base::Unretained(this)));
143 callback.Run(instance_id_);
144 ExecutePendingRequests();
147 void MediaRouterMojoImpl::OnIssue(const interfaces::IssuePtr issue) {
148 DCHECK(thread_checker_.CalledOnValidThread());
149 DVLOG_WITH_INSTANCE(1) << "OnIssue " << issue->title;
150 const Issue& issue_converted = issue.To<Issue>();
151 issue_manager_.AddIssue(issue_converted);
154 void MediaRouterMojoImpl::OnSinksReceived(
155 const mojo::String& media_source,
156 mojo::Array<interfaces::MediaSinkPtr> sinks) {
157 DCHECK(thread_checker_.CalledOnValidThread());
159 DVLOG_WITH_INSTANCE(1) << "OnSinksReceived";
160 std::vector<MediaSink> sinks_converted;
161 sinks_converted.reserve(sinks.size());
163 for (size_t i = 0; i < sinks.size(); ++i) {
164 sinks_converted.push_back(sinks[i].To<MediaSink>());
167 auto it = sinks_observers_.find(media_source);
168 if (it == sinks_observers_.end()) {
169 DVLOG_WITH_INSTANCE(1)
170 << "Received sink list without any active observers: " << media_source;
171 } else {
172 FOR_EACH_OBSERVER(MediaSinksObserver, *it->second,
173 OnSinksReceived(sinks_converted));
177 void MediaRouterMojoImpl::OnRoutesUpdated(
178 mojo::Array<interfaces::MediaRoutePtr> routes) {
179 DCHECK(thread_checker_.CalledOnValidThread());
181 DVLOG_WITH_INSTANCE(1) << "OnRoutesUpdated";
183 std::vector<MediaRoute> routes_converted;
184 routes_converted.reserve(routes.size());
186 for (size_t i = 0; i < routes.size(); ++i) {
187 routes_converted.push_back(routes[i].To<MediaRoute>());
190 FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_,
191 OnRoutesUpdated(routes_converted));
194 void MediaRouterMojoImpl::CreateRoute(
195 const MediaSource::Id& source_id,
196 const MediaSink::Id& sink_id,
197 const GURL& origin,
198 int tab_id,
199 const std::vector<MediaRouteResponseCallback>& callbacks) {
200 DCHECK(thread_checker_.CalledOnValidThread());
202 if (!origin.is_valid()) {
203 DVLOG_WITH_INSTANCE(1) << "Invalid origin: " << origin;
204 for (const MediaRouteResponseCallback& callback : callbacks)
205 callback.Run(nullptr, "", "Invalid origin");
206 return;
208 RunOrDefer(base::Bind(
209 &MediaRouterMojoImpl::DoCreateRoute, base::Unretained(this), source_id,
210 sink_id, origin.is_empty() ? "" : origin.spec(), tab_id, callbacks));
213 void MediaRouterMojoImpl::JoinRoute(
214 const MediaSource::Id& source_id,
215 const std::string& presentation_id,
216 const GURL& origin,
217 int tab_id,
218 const std::vector<MediaRouteResponseCallback>& callbacks) {
219 DCHECK(thread_checker_.CalledOnValidThread());
221 if (!origin.is_valid()) {
222 DVLOG_WITH_INSTANCE(1) << "Invalid origin: " << origin;
223 for (const MediaRouteResponseCallback& callback : callbacks)
224 callback.Run(nullptr, "", "Invalid origin");
225 return;
227 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoJoinRoute,
228 base::Unretained(this), source_id, presentation_id,
229 origin.is_empty() ? "" : origin.spec(), tab_id,
230 callbacks));
233 void MediaRouterMojoImpl::CloseRoute(const MediaRoute::Id& route_id) {
234 DCHECK(thread_checker_.CalledOnValidThread());
236 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoCloseRoute,
237 base::Unretained(this), route_id));
240 void MediaRouterMojoImpl::SendRouteMessage(
241 const MediaRoute::Id& route_id,
242 const std::string& message,
243 const SendRouteMessageCallback& callback) {
244 DCHECK(thread_checker_.CalledOnValidThread());
246 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoSendSessionMessage,
247 base::Unretained(this), route_id, message, callback));
250 void MediaRouterMojoImpl::SendRouteBinaryMessage(
251 const MediaRoute::Id& route_id,
252 scoped_ptr<std::vector<uint8>> data,
253 const SendRouteMessageCallback& callback) {
254 DCHECK(thread_checker_.CalledOnValidThread());
256 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoSendSessionBinaryMessage,
257 base::Unretained(this), route_id,
258 base::Passed(data.Pass()), callback));
261 void MediaRouterMojoImpl::ClearIssue(const Issue::Id& issue_id) {
262 DCHECK(thread_checker_.CalledOnValidThread());
263 issue_manager_.ClearIssue(issue_id);
266 void MediaRouterMojoImpl::OnPresentationSessionDetached(
267 const MediaRoute::Id& route_id) {
268 DCHECK(thread_checker_.CalledOnValidThread());
269 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoOnPresentationSessionDetached,
270 base::Unretained(this), route_id));
273 void MediaRouterMojoImpl::RegisterMediaSinksObserver(
274 MediaSinksObserver* observer) {
275 DCHECK(thread_checker_.CalledOnValidThread());
277 // Create an observer list for the media source and add |observer|
278 // to it. Fail if |observer| is already registered.
279 const std::string& source_id = observer->source().id();
280 base::ObserverList<MediaSinksObserver>* observer_list =
281 sinks_observers_.get(source_id);
282 if (!observer_list) {
283 observer_list = new base::ObserverList<MediaSinksObserver>;
284 sinks_observers_.add(source_id, make_scoped_ptr(observer_list));
285 } else {
286 DCHECK(!observer_list->HasObserver(observer));
289 // We need to call DoStartObservingMediaSinks every time an observer is
290 // added to ensure the observer will be notified with a fresh set of results.
291 // TODO(imcheng): Implement caching. (crbug.com/492451)
292 observer_list->AddObserver(observer);
293 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStartObservingMediaSinks,
294 base::Unretained(this), source_id));
297 void MediaRouterMojoImpl::UnregisterMediaSinksObserver(
298 MediaSinksObserver* observer) {
299 DCHECK(thread_checker_.CalledOnValidThread());
301 const MediaSource::Id& source_id = observer->source().id();
302 auto* observer_list = sinks_observers_.get(source_id);
303 if (!observer_list || !observer_list->HasObserver(observer)) {
304 return;
307 // If we are removing the final observer for the source, then stop
308 // observing sinks for it.
309 // might_have_observers() is reliable here on the assumption that this call
310 // is not inside the ObserverList iteration.
311 observer_list->RemoveObserver(observer);
312 if (!observer_list->might_have_observers()) {
313 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStopObservingMediaSinks,
314 base::Unretained(this), source_id));
315 sinks_observers_.erase(source_id);
319 void MediaRouterMojoImpl::RegisterMediaRoutesObserver(
320 MediaRoutesObserver* observer) {
321 DCHECK(thread_checker_.CalledOnValidThread());
322 DCHECK(!routes_observers_.HasObserver(observer));
324 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStartObservingMediaRoutes,
325 base::Unretained(this)));
326 routes_observers_.AddObserver(observer);
329 void MediaRouterMojoImpl::UnregisterMediaRoutesObserver(
330 MediaRoutesObserver* observer) {
331 if (!routes_observers_.HasObserver(observer))
332 return;
334 routes_observers_.RemoveObserver(observer);
335 if (!routes_observers_.might_have_observers()) {
336 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStopObservingMediaRoutes,
337 base::Unretained(this)));
341 void MediaRouterMojoImpl::RegisterIssuesObserver(IssuesObserver* observer) {
342 DCHECK(thread_checker_.CalledOnValidThread());
343 issue_manager_.RegisterObserver(observer);
346 void MediaRouterMojoImpl::UnregisterIssuesObserver(IssuesObserver* observer) {
347 DCHECK(thread_checker_.CalledOnValidThread());
348 issue_manager_.UnregisterObserver(observer);
351 void MediaRouterMojoImpl::RegisterPresentationSessionMessagesObserver(
352 PresentationSessionMessagesObserver* observer) {
353 DCHECK(thread_checker_.CalledOnValidThread());
354 DCHECK(observer);
355 const MediaRoute::Id& route_id = observer->route_id();
356 auto* observer_list = messages_observers_.get(route_id);
357 if (!observer_list) {
358 observer_list = new base::ObserverList<PresentationSessionMessagesObserver>;
359 messages_observers_.add(route_id, make_scoped_ptr(observer_list));
360 } else {
361 DCHECK(!observer_list->HasObserver(observer));
364 bool should_listen = !observer_list->might_have_observers();
365 observer_list->AddObserver(observer);
366 if (should_listen) {
367 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoListenForRouteMessages,
368 base::Unretained(this), route_id));
372 void MediaRouterMojoImpl::UnregisterPresentationSessionMessagesObserver(
373 PresentationSessionMessagesObserver* observer) {
374 DCHECK(thread_checker_.CalledOnValidThread());
375 DCHECK(observer);
377 const MediaRoute::Id& route_id = observer->route_id();
378 auto* observer_list = messages_observers_.get(route_id);
379 if (!observer_list || !observer_list->HasObserver(observer))
380 return;
382 observer_list->RemoveObserver(observer);
383 if (!observer_list->might_have_observers()) {
384 messages_observers_.erase(route_id);
385 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStopListeningForRouteMessages,
386 base::Unretained(this), route_id));
390 void MediaRouterMojoImpl::DoCreateRoute(
391 const MediaSource::Id& source_id,
392 const MediaSink::Id& sink_id,
393 const std::string& origin,
394 int tab_id,
395 const std::vector<MediaRouteResponseCallback>& callbacks) {
396 std::string presentation_id("mr_");
397 presentation_id += base::GenerateGUID();
398 DVLOG_WITH_INSTANCE(1) << "DoCreateRoute " << source_id << "=>" << sink_id
399 << ", presentation ID: " << presentation_id;
400 media_route_provider_->CreateRoute(
401 source_id, sink_id, presentation_id, origin, tab_id,
402 base::Bind(&RouteResponseReceived, presentation_id, callbacks));
405 void MediaRouterMojoImpl::DoJoinRoute(
406 const MediaSource::Id& source_id,
407 const std::string& presentation_id,
408 const std::string& origin,
409 int tab_id,
410 const std::vector<MediaRouteResponseCallback>& callbacks) {
411 DVLOG_WITH_INSTANCE(1) << "DoJoinRoute " << source_id
412 << ", presentation ID: " << presentation_id;
413 media_route_provider_->JoinRoute(
414 source_id, presentation_id, origin, tab_id,
415 base::Bind(&RouteResponseReceived, presentation_id, callbacks));
418 void MediaRouterMojoImpl::DoCloseRoute(const MediaRoute::Id& route_id) {
419 DVLOG_WITH_INSTANCE(1) << "DoCloseRoute " << route_id;
420 media_route_provider_->CloseRoute(route_id);
423 void MediaRouterMojoImpl::DoSendSessionMessage(
424 const MediaRoute::Id& route_id,
425 const std::string& message,
426 const SendRouteMessageCallback& callback) {
427 DVLOG_WITH_INSTANCE(1) << "SendRouteMessage " << route_id;
428 media_route_provider_->SendRouteMessage(route_id, message, callback);
431 void MediaRouterMojoImpl::DoSendSessionBinaryMessage(
432 const MediaRoute::Id& route_id,
433 scoped_ptr<std::vector<uint8>> data,
434 const SendRouteMessageCallback& callback) {
435 DVLOG_WITH_INSTANCE(1) << "SendRouteBinaryMessage " << route_id;
436 mojo::Array<uint8> mojo_array;
437 mojo_array.Swap(data.get());
438 media_route_provider_->SendRouteBinaryMessage(route_id, mojo_array.Pass(),
439 callback);
442 void MediaRouterMojoImpl::DoListenForRouteMessages(
443 const MediaRoute::Id& route_id) {
444 DVLOG_WITH_INSTANCE(1) << "ListenForRouteMessages";
445 if (!ContainsValue(route_ids_listening_for_messages_, route_id)) {
446 route_ids_listening_for_messages_.insert(route_id);
447 media_route_provider_->ListenForRouteMessages(
448 route_id, base::Bind(&MediaRouterMojoImpl::OnRouteMessagesReceived,
449 base::Unretained(this), route_id));
453 void MediaRouterMojoImpl::DoStopListeningForRouteMessages(
454 const MediaRoute::Id& route_id) {
455 DVLOG_WITH_INSTANCE(1) << "StopListeningForRouteMessages";
457 // No need to erase |route_ids_listening_for_messages_| entry here.
458 // It will be removed when there are no more observers by the time
459 // |OnRouteMessagesReceived| is invoked.
460 media_route_provider_->StopListeningForRouteMessages(route_id);
463 void MediaRouterMojoImpl::OnRouteMessagesReceived(
464 const MediaRoute::Id& route_id,
465 mojo::Array<interfaces::RouteMessagePtr> messages,
466 bool error) {
467 DVLOG(1) << "OnRouteMessagesReceived";
469 // If |messages| is null, then no more messages will come from this route.
470 // We can stop listening.
471 if (error) {
472 DVLOG(2) << "Encountered error in OnRouteMessagesReceived for " << route_id;
473 route_ids_listening_for_messages_.erase(route_id);
474 return;
477 // Check if there are any observers remaining. If not, the messages
478 // can be discarded and we can stop listening for the next batch of messages.
479 auto* observer_list = messages_observers_.get(route_id);
480 if (!observer_list) {
481 route_ids_listening_for_messages_.erase(route_id);
482 return;
485 // If |messages| is empty, then |StopListeningForRouteMessages| was invoked
486 // but we have added back an observer since. Keep listening for more messages,
487 // but do not notify observers with empty list.
488 if (!messages.storage().empty()) {
489 ScopedVector<content::PresentationSessionMessage> session_messages;
490 session_messages.reserve(messages.size());
491 for (size_t i = 0; i < messages.size(); ++i) {
492 session_messages.push_back(
493 ConvertToPresentationSessionMessage(messages[i].Pass()).Pass());
495 base::ObserverList<PresentationSessionMessagesObserver>::Iterator
496 observer_it(observer_list);
497 bool single_observer =
498 observer_it.GetNext() != nullptr && observer_it.GetNext() == nullptr;
499 FOR_EACH_OBSERVER(PresentationSessionMessagesObserver, *observer_list,
500 OnMessagesReceived(session_messages, single_observer));
503 // Listen for more messages.
504 media_route_provider_->ListenForRouteMessages(
505 route_id, base::Bind(&MediaRouterMojoImpl::OnRouteMessagesReceived,
506 base::Unretained(this), route_id));
509 void MediaRouterMojoImpl::DoOnPresentationSessionDetached(
510 const MediaRoute::Id& route_id) {
511 DVLOG_WITH_INSTANCE(1) << "DoOnPresentationSessionDetached " << route_id;
512 media_route_provider_->OnPresentationSessionDetached(route_id);
515 void MediaRouterMojoImpl::DoStartObservingMediaSinks(
516 const MediaSource::Id& source_id) {
517 DVLOG_WITH_INSTANCE(1) << "DoStartObservingMediaSinks: " << source_id;
518 media_route_provider_->StartObservingMediaSinks(source_id);
521 void MediaRouterMojoImpl::DoStopObservingMediaSinks(
522 const MediaSource::Id& source_id) {
523 DVLOG_WITH_INSTANCE(1) << "DoStopObservingMediaSinks: " << source_id;
524 media_route_provider_->StopObservingMediaSinks(source_id);
527 void MediaRouterMojoImpl::DoStartObservingMediaRoutes() {
528 DVLOG_WITH_INSTANCE(1) << "DoStartObservingMediaRoutes";
529 media_route_provider_->StartObservingMediaRoutes();
532 void MediaRouterMojoImpl::DoStopObservingMediaRoutes() {
533 DVLOG_WITH_INSTANCE(1) << "DoStopObservingMediaRoutes";
534 media_route_provider_->StopObservingMediaRoutes();
537 void MediaRouterMojoImpl::EnqueueTask(const base::Closure& closure) {
538 pending_requests_.push_back(closure);
539 DVLOG_WITH_INSTANCE(2) << "EnqueueTask (queue-length="
540 << pending_requests_.size() << ")";
543 void MediaRouterMojoImpl::RunOrDefer(const base::Closure& request) {
544 DCHECK(event_page_tracker_);
546 if (media_route_provider_extension_id_.empty()) {
547 DVLOG_WITH_INSTANCE(1) << "Extension ID not known yet.";
548 EnqueueTask(request);
549 } else if (event_page_tracker_->IsEventPageSuspended(
550 media_route_provider_extension_id_)) {
551 DVLOG_WITH_INSTANCE(1) << "Waking event page.";
552 EnqueueTask(request);
553 if (!event_page_tracker_->WakeEventPage(
554 media_route_provider_extension_id_,
555 base::Bind(&EventPageWakeComplete))) {
556 LOG(ERROR) << "An error encountered while waking the event page.";
558 media_route_provider_.reset();
559 } else if (!media_route_provider_) {
560 DVLOG_WITH_INSTANCE(1) << "Extension is awake, awaiting ProvideMediaRouter "
561 " to be called.";
562 EnqueueTask(request);
563 } else {
564 request.Run();
568 void MediaRouterMojoImpl::ExecutePendingRequests() {
569 DCHECK(thread_checker_.CalledOnValidThread());
570 DCHECK(media_route_provider_);
571 DCHECK(event_page_tracker_);
572 DCHECK(!media_route_provider_extension_id_.empty());
574 if (event_page_tracker_->IsEventPageSuspended(
575 media_route_provider_extension_id_)) {
576 DVLOG_WITH_INSTANCE(1)
577 << "ExecutePendingRequests was called while extension is suspended.";
578 return;
581 for (const auto& next_request : pending_requests_)
582 next_request.Run();
584 pending_requests_.clear();
587 } // namespace media_router