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"
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
{
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
;
39 if (media_route
.is_null()) {
41 DCHECK(!error_text
.is_null());
42 error
= !error_text
.get().empty() ? error_text
.get() : "Unknown error.";
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
) {
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
);
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());
83 NOTREACHED() << "Invalid route message type " << input
->type
;
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());
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
));
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());
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();
134 void MediaRouterMojoImpl::RegisterMediaRouteProvider(
135 interfaces::MediaRouteProviderPtr media_route_provider_ptr
,
136 const interfaces::MediaRouter::RegisterMediaRouteProviderCallback
&
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
;
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
,
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");
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
,
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");
227 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoJoinRoute
,
228 base::Unretained(this), source_id
, presentation_id
,
229 origin
.is_empty() ? "" : origin
.spec(), tab_id
,
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
);
264 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoClearIssue
,
265 base::Unretained(this), issue_id
));
268 void MediaRouterMojoImpl::RegisterMediaSinksObserver(
269 MediaSinksObserver
* observer
) {
270 DCHECK(thread_checker_
.CalledOnValidThread());
272 // Create an observer list for the media source and add |observer|
273 // to it. Fail if |observer| is already registered.
274 const std::string
& source_id
= observer
->source().id();
275 base::ObserverList
<MediaSinksObserver
>* observer_list
=
276 sinks_observers_
.get(source_id
);
277 if (!observer_list
) {
278 observer_list
= new base::ObserverList
<MediaSinksObserver
>;
279 sinks_observers_
.add(source_id
, make_scoped_ptr(observer_list
));
281 DCHECK(!observer_list
->HasObserver(observer
));
284 // We need to call DoStartObservingMediaSinks every time an observer is
285 // added to ensure the observer will be notified with a fresh set of results.
286 // TODO(imcheng): Implement caching. (crbug.com/492451)
287 observer_list
->AddObserver(observer
);
288 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStartObservingMediaSinks
,
289 base::Unretained(this), source_id
));
292 void MediaRouterMojoImpl::UnregisterMediaSinksObserver(
293 MediaSinksObserver
* observer
) {
294 DCHECK(thread_checker_
.CalledOnValidThread());
296 const MediaSource::Id
& source_id
= observer
->source().id();
297 auto* observer_list
= sinks_observers_
.get(source_id
);
298 if (!observer_list
|| !observer_list
->HasObserver(observer
)) {
302 // If we are removing the final observer for the source, then stop
303 // observing sinks for it.
304 // might_have_observers() is reliable here on the assumption that this call
305 // is not inside the ObserverList iteration.
306 observer_list
->RemoveObserver(observer
);
307 if (!observer_list
->might_have_observers()) {
308 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStopObservingMediaSinks
,
309 base::Unretained(this), source_id
));
310 sinks_observers_
.erase(source_id
);
314 void MediaRouterMojoImpl::RegisterMediaRoutesObserver(
315 MediaRoutesObserver
* observer
) {
316 DCHECK(thread_checker_
.CalledOnValidThread());
317 DCHECK(!routes_observers_
.HasObserver(observer
));
319 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStartObservingMediaRoutes
,
320 base::Unretained(this)));
321 routes_observers_
.AddObserver(observer
);
324 void MediaRouterMojoImpl::UnregisterMediaRoutesObserver(
325 MediaRoutesObserver
* observer
) {
326 if (!routes_observers_
.HasObserver(observer
))
329 routes_observers_
.RemoveObserver(observer
);
330 if (!routes_observers_
.might_have_observers()) {
331 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoStopObservingMediaRoutes
,
332 base::Unretained(this)));
336 void MediaRouterMojoImpl::RegisterIssuesObserver(IssuesObserver
* observer
) {
337 DCHECK(thread_checker_
.CalledOnValidThread());
338 issue_manager_
.RegisterObserver(observer
);
341 void MediaRouterMojoImpl::UnregisterIssuesObserver(IssuesObserver
* observer
) {
342 DCHECK(thread_checker_
.CalledOnValidThread());
343 issue_manager_
.UnregisterObserver(observer
);
346 void MediaRouterMojoImpl::RegisterPresentationSessionMessagesObserver(
347 PresentationSessionMessagesObserver
* observer
) {
348 DCHECK(thread_checker_
.CalledOnValidThread());
350 const MediaRoute::Id
& route_id
= observer
->route_id();
351 auto* observer_list
= messages_observers_
.get(route_id
);
352 if (!observer_list
) {
353 observer_list
= new base::ObserverList
<PresentationSessionMessagesObserver
>;
354 messages_observers_
.add(route_id
, make_scoped_ptr(observer_list
));
356 DCHECK(!observer_list
->HasObserver(observer
));
359 bool should_listen
= !observer_list
->might_have_observers();
360 observer_list
->AddObserver(observer
);
362 RunOrDefer(base::Bind(&MediaRouterMojoImpl::DoListenForRouteMessages
,
363 base::Unretained(this), route_id
));
367 void MediaRouterMojoImpl::UnregisterPresentationSessionMessagesObserver(
368 PresentationSessionMessagesObserver
* observer
) {
369 DCHECK(thread_checker_
.CalledOnValidThread());
372 const MediaRoute::Id
& route_id
= observer
->route_id();
373 auto* observer_list
= messages_observers_
.get(route_id
);
374 if (!observer_list
|| !observer_list
->HasObserver(observer
))
377 observer_list
->RemoveObserver(observer
);
378 if (!observer_list
->might_have_observers())
379 messages_observers_
.erase(route_id
);
380 // TODO(imcheng): Queue a task to stop listening for messages by asking
381 // the extension to invoke the oustanding Mojo callback with empty list. We
382 // don't want the Mojo callback to exist indefinitely on the extension side
383 // and there is currently no way to cancel the callback from this side.
386 void MediaRouterMojoImpl::DoCreateRoute(
387 const MediaSource::Id
& source_id
,
388 const MediaSink::Id
& sink_id
,
389 const std::string
& origin
,
391 const std::vector
<MediaRouteResponseCallback
>& callbacks
) {
392 std::string
presentation_id("mr_");
393 presentation_id
+= base::GenerateGUID();
394 DVLOG_WITH_INSTANCE(1) << "DoCreateRoute " << source_id
<< "=>" << sink_id
395 << ", presentation ID: " << presentation_id
;
396 media_route_provider_
->CreateRoute(
397 source_id
, sink_id
, presentation_id
, origin
, tab_id
,
398 base::Bind(&RouteResponseReceived
, presentation_id
, callbacks
));
401 void MediaRouterMojoImpl::DoJoinRoute(
402 const MediaSource::Id
& source_id
,
403 const std::string
& presentation_id
,
404 const std::string
& origin
,
406 const std::vector
<MediaRouteResponseCallback
>& callbacks
) {
407 DVLOG_WITH_INSTANCE(1) << "DoJoinRoute " << source_id
408 << ", presentation ID: " << presentation_id
;
409 media_route_provider_
->JoinRoute(
410 source_id
, presentation_id
, origin
, tab_id
,
411 base::Bind(&RouteResponseReceived
, presentation_id
, callbacks
));
414 void MediaRouterMojoImpl::DoCloseRoute(const MediaRoute::Id
& route_id
) {
415 DVLOG_WITH_INSTANCE(1) << "DoCloseRoute " << route_id
;
416 media_route_provider_
->CloseRoute(route_id
);
419 void MediaRouterMojoImpl::DoSendSessionMessage(
420 const MediaRoute::Id
& route_id
,
421 const std::string
& message
,
422 const SendRouteMessageCallback
& callback
) {
423 DVLOG_WITH_INSTANCE(1) << "SendRouteMessage " << route_id
;
424 media_route_provider_
->SendRouteMessage(route_id
, message
, callback
);
427 void MediaRouterMojoImpl::DoSendSessionBinaryMessage(
428 const MediaRoute::Id
& route_id
,
429 scoped_ptr
<std::vector
<uint8
>> data
,
430 const SendRouteMessageCallback
& callback
) {
431 DVLOG_WITH_INSTANCE(1) << "SendRouteBinaryMessage " << route_id
;
432 mojo::Array
<uint8
> mojo_array
;
433 mojo_array
.Swap(data
.get());
434 media_route_provider_
->SendRouteBinaryMessage(route_id
, mojo_array
.Pass(),
438 void MediaRouterMojoImpl::DoListenForRouteMessages(
439 const MediaRoute::Id
& route_id
) {
440 DVLOG_WITH_INSTANCE(1) << "ListenForRouteMessages";
441 if (!ContainsValue(route_ids_listening_for_messages_
, route_id
)) {
442 route_ids_listening_for_messages_
.insert(route_id
);
443 media_route_provider_
->ListenForRouteMessages(
444 route_id
, base::Bind(&MediaRouterMojoImpl::OnRouteMessagesReceived
,
445 base::Unretained(this), route_id
));
449 void MediaRouterMojoImpl::OnRouteMessagesReceived(
450 const MediaRoute::Id
& route_id
,
451 mojo::Array
<interfaces::RouteMessagePtr
> messages
) {
452 DVLOG(1) << "OnRouteMessagesReceived";
454 // Check if there are any observers remaining. If not, the messages
455 // can be discarded and we can stop listening for the next batch of messages.
456 auto* observer_list
= messages_observers_
.get(route_id
);
457 if (!observer_list
) {
458 route_ids_listening_for_messages_
.erase(route_id
);
462 // Empty |messages| means we told the extension that we were no longer
463 // listening for messages on that route. But since now we have observers
464 // again, we should keep listening.
465 if (messages
.storage().empty()) {
466 DVLOG(2) << "Received empty messages for " << route_id
;
468 ScopedVector
<content::PresentationSessionMessage
> session_messages
;
469 session_messages
.reserve(messages
.size());
470 for (size_t i
= 0; i
< messages
.size(); ++i
) {
471 session_messages
.push_back(
472 ConvertToPresentationSessionMessage(messages
[i
].Pass()).Pass());
475 // TODO(imcheng): If there is only 1 observer, we should be able to pass
476 // the messages to avoid additional copies. (crbug.com/517234)
477 FOR_EACH_OBSERVER(PresentationSessionMessagesObserver
, *observer_list
,
478 OnMessagesReceived(session_messages
));
481 // Listen for more messages.
482 media_route_provider_
->ListenForRouteMessages(
483 route_id
, base::Bind(&MediaRouterMojoImpl::OnRouteMessagesReceived
,
484 base::Unretained(this), route_id
));
487 void MediaRouterMojoImpl::DoClearIssue(const Issue::Id
& issue_id
) {
488 DVLOG_WITH_INSTANCE(1) << "DoClearIssue " << issue_id
;
489 media_route_provider_
->ClearIssue(issue_id
);
492 void MediaRouterMojoImpl::DoStartObservingMediaSinks(
493 const MediaSource::Id
& source_id
) {
494 DVLOG_WITH_INSTANCE(1) << "DoStartObservingMediaSinks: " << source_id
;
495 media_route_provider_
->StartObservingMediaSinks(source_id
);
498 void MediaRouterMojoImpl::DoStopObservingMediaSinks(
499 const MediaSource::Id
& source_id
) {
500 DVLOG_WITH_INSTANCE(1) << "DoStopObservingMediaSinks: " << source_id
;
501 media_route_provider_
->StopObservingMediaSinks(source_id
);
504 void MediaRouterMojoImpl::DoStartObservingMediaRoutes() {
505 DVLOG_WITH_INSTANCE(1) << "DoStartObservingMediaRoutes";
506 media_route_provider_
->StartObservingMediaRoutes();
509 void MediaRouterMojoImpl::DoStopObservingMediaRoutes() {
510 DVLOG_WITH_INSTANCE(1) << "DoStopObservingMediaRoutes";
511 media_route_provider_
->StopObservingMediaRoutes();
514 void MediaRouterMojoImpl::EnqueueTask(const base::Closure
& closure
) {
515 pending_requests_
.push_back(closure
);
516 DVLOG_WITH_INSTANCE(2) << "EnqueueTask (queue-length="
517 << pending_requests_
.size() << ")";
520 void MediaRouterMojoImpl::RunOrDefer(const base::Closure
& request
) {
521 DCHECK(event_page_tracker_
);
523 if (media_route_provider_extension_id_
.empty()) {
524 DVLOG_WITH_INSTANCE(1) << "Extension ID not known yet.";
525 EnqueueTask(request
);
526 } else if (event_page_tracker_
->IsEventPageSuspended(
527 media_route_provider_extension_id_
)) {
528 DVLOG_WITH_INSTANCE(1) << "Waking event page.";
529 EnqueueTask(request
);
530 if (!event_page_tracker_
->WakeEventPage(
531 media_route_provider_extension_id_
,
532 base::Bind(&EventPageWakeComplete
))) {
533 LOG(ERROR
) << "An error encountered while waking the event page.";
535 media_route_provider_
.reset();
536 } else if (!media_route_provider_
) {
537 DVLOG_WITH_INSTANCE(1) << "Extension is awake, awaiting ProvideMediaRouter "
539 EnqueueTask(request
);
545 void MediaRouterMojoImpl::ExecutePendingRequests() {
546 DCHECK(thread_checker_
.CalledOnValidThread());
547 DCHECK(media_route_provider_
);
548 DCHECK(event_page_tracker_
);
549 DCHECK(!media_route_provider_extension_id_
.empty());
551 if (event_page_tracker_
->IsEventPageSuspended(
552 media_route_provider_extension_id_
)) {
553 DVLOG_WITH_INSTANCE(1)
554 << "ExecutePendingRequests was called while extension is suspended.";
558 for (const auto& next_request
: pending_requests_
)
561 pending_requests_
.clear();
564 } // namespace media_router