File: controller_presentation_service_delegate_impl.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (770 lines) | stat: -rw-r--r-- 30,552 bytes parent folder | download | duplicates (3)
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/media_router/browser/presentation/controller_presentation_service_delegate_impl.h"

#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/containers/small_map.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/media_router/browser/media_router.h"
#include "components/media_router/browser/media_router_dialog_controller.h"
#include "components/media_router/browser/media_router_factory.h"
#include "components/media_router/browser/media_router_metrics.h"
#include "components/media_router/browser/presentation/browser_presentation_connection_proxy.h"
#include "components/media_router/browser/presentation/local_presentation_manager.h"
#include "components/media_router/browser/presentation/local_presentation_manager_factory.h"
#include "components/media_router/browser/presentation/presentation_media_sinks_observer.h"
#include "components/media_router/browser/presentation_connection_message_observer.h"
#include "components/media_router/common/media_route.h"
#include "components/media_router/common/media_sink.h"
#include "components/media_router/common/media_source.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/presentation_observer.h"
#include "content/public/browser/presentation_request.h"
#include "content/public/browser/presentation_screen_availability_listener.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "url/gurl.h"

using blink::mojom::PresentationConnection;
using blink::mojom::PresentationError;
using blink::mojom::PresentationErrorType;
using blink::mojom::PresentationInfo;
using blink::mojom::ScreenAvailability;
using content::RenderFrameHost;

namespace media_router {

namespace {

using DelegateObserver = content::PresentationServiceDelegate::Observer;

// Gets the last committed URL for the render frame specified by
// |render_frame_host_id|.
url::Origin GetLastCommittedURLForFrame(
    content::GlobalRenderFrameHostId render_frame_host_id) {
  RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
      render_frame_host_id.child_id, render_frame_host_id.frame_routing_id);
  DCHECK(render_frame_host);
  return render_frame_host->GetLastCommittedOrigin();
}

bool ArePresentationRequestsEqual(
    const content::PresentationRequest& request1,
    const content::PresentationRequest& request2) {
  return request1.render_frame_host_id == request2.render_frame_host_id &&
         request1.presentation_urls == request2.presentation_urls &&
         ((request1.frame_origin.opaque() && request2.frame_origin.opaque()) ||
          (request1.frame_origin == request2.frame_origin));
}

}  // namespace

// PresentationFrame interfaces with MediaRouter to maintain the current state
// of Presentation API within a single render frame, such as the set of
// PresentationAvailability listeners and PresentationConnections.
// Instances are lazily created when certain Presentation API is invoked on a
// frame, and are owned by ControllerPresentationServiceDelegateImpl.
// Instances are destroyed when the corresponding frame navigates, or when it
// is destroyed.
class PresentationFrame {
 public:
  PresentationFrame(
      const content::GlobalRenderFrameHostId& render_frame_host_id,
      content::WebContents* web_contents,
      MediaRouter* router);
  ~PresentationFrame();

  // Mirror corresponding APIs in ControllerPresentationServiceDelegateImpl.
  bool SetScreenAvailabilityListener(
      content::PresentationScreenAvailabilityListener* listener);
  void RemoveScreenAvailabilityListener(
      content::PresentationScreenAvailabilityListener* listener);
  bool HasScreenAvailabilityListenerForTest(
      const MediaSource::Id& source_id) const;
  void ListenForConnectionStateChange(
      const PresentationInfo& connection,
      const content::PresentationConnectionStateChangedCallback&
          state_changed_cb);

  void Reset();

  MediaRoute::Id GetRouteId(const std::string& presentation_id) const;

  void AddPresentation(const PresentationInfo& presentation_info,
                       const MediaRoute& route);
  void ConnectToPresentation(
      const PresentationInfo& presentation_info,
      mojo::PendingRemote<PresentationConnection> controller_connection_remote,
      mojo::PendingReceiver<PresentationConnection>
          receiver_connection_receiver);
  void RemovePresentation(const std::string& presentation_id);

  const base::small_map<std::map<std::string, MediaRoute>>&
  presentation_id_to_route() const {
    return presentation_id_to_route_;
  }

 private:
  base::small_map<std::map<std::string, MediaRoute>> presentation_id_to_route_;
  base::small_map<
      std::map<std::string, std::unique_ptr<PresentationMediaSinksObserver>>>
      url_to_sinks_observer_;
  std::unordered_map<MediaRoute::Id, base::CallbackListSubscription>
      connection_state_subscriptions_;
  std::unordered_map<MediaRoute::Id,
                     std::unique_ptr<BrowserPresentationConnectionProxy>>
      browser_connection_proxies_;

  content::GlobalRenderFrameHostId render_frame_host_id_;

  // References to the owning WebContents, and the corresponding MediaRouter.
  raw_ptr<content::WebContents> web_contents_;
  raw_ptr<MediaRouter> router_;
};

PresentationFrame::PresentationFrame(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    content::WebContents* web_contents,
    MediaRouter* router)
    : render_frame_host_id_(render_frame_host_id),
      web_contents_(web_contents),
      router_(router) {
  DCHECK(web_contents_);
  DCHECK(router_);
}

PresentationFrame::~PresentationFrame() = default;

MediaRoute::Id PresentationFrame::GetRouteId(
    const std::string& presentation_id) const {
  auto it = presentation_id_to_route_.find(presentation_id);
  return it != presentation_id_to_route_.end() ? it->second.media_route_id()
                                               : "";
}

bool PresentationFrame::SetScreenAvailabilityListener(
    content::PresentationScreenAvailabilityListener* listener) {
  GURL url = listener->GetAvailabilityUrl();
  if (!IsValidPresentationUrl(url)) {
    listener->OnScreenAvailabilityChanged(
        ScreenAvailability::SOURCE_NOT_SUPPORTED);
    return false;
  }

  MediaRouterMetrics::RecordPresentationUrlType(url);

  MediaSource source = MediaSource::ForPresentationUrl(url);
  auto& sinks_observer = url_to_sinks_observer_[source.id()];
  if (sinks_observer && sinks_observer->listener() == listener) {
    return false;
  }

  sinks_observer = std::make_unique<PresentationMediaSinksObserver>(
      router_, listener, source,
      GetLastCommittedURLForFrame(render_frame_host_id_));

  if (!sinks_observer->Init()) {
    url_to_sinks_observer_.erase(source.id());
    listener->OnScreenAvailabilityChanged(ScreenAvailability::DISABLED);
    return false;
  }

  return true;
}

void PresentationFrame::RemoveScreenAvailabilityListener(
    content::PresentationScreenAvailabilityListener* listener) {
  MediaSource source =
      MediaSource::ForPresentationUrl(listener->GetAvailabilityUrl());
  auto sinks_observer_it = url_to_sinks_observer_.find(source.id());
  if (sinks_observer_it != url_to_sinks_observer_.end() &&
      sinks_observer_it->second->listener() == listener) {
    url_to_sinks_observer_.erase(sinks_observer_it);
  }
}

bool PresentationFrame::HasScreenAvailabilityListenerForTest(
    const MediaSource::Id& source_id) const {
  return url_to_sinks_observer_.find(source_id) != url_to_sinks_observer_.end();
}

void PresentationFrame::Reset() {
  // Create a copy here to avoid `pid_route` being invalidated while iterating.
  // `router->DetachRoute()` might cause a Presentation route to be terminated
  // and removed from `presentation_id_to_route_`.
  auto presentation_id_to_route_copy(presentation_id_to_route_);
  for (const auto& pid_route : presentation_id_to_route_copy) {
    if (pid_route.second.is_local_presentation()) {
      auto* local_presentation_manager =
          LocalPresentationManagerFactory::GetOrCreateForWebContents(
              web_contents_);
      local_presentation_manager->UnregisterLocalPresentationController(
          pid_route.first, render_frame_host_id_);
    } else {
      // We avoid using `router_` here because it may have been invalidated if
      // this method is called during profile shutdown. This is a speculative
      // fix for crbug.com/1219904.
      MediaRouter* router = MediaRouterFactory::GetApiForBrowserContextIfExists(
          web_contents_->GetBrowserContext());
      if (router) {
        router->DetachRoute(pid_route.second.media_route_id());
      }
    }
  }

  presentation_id_to_route_.clear();
  url_to_sinks_observer_.clear();
  connection_state_subscriptions_.clear();
  browser_connection_proxies_.clear();
}

void PresentationFrame::AddPresentation(
    const PresentationInfo& presentation_info,
    const MediaRoute& route) {
  presentation_id_to_route_.emplace(presentation_info.id, route);
}

void PresentationFrame::ConnectToPresentation(
    const PresentationInfo& presentation_info,
    mojo::PendingRemote<PresentationConnection> controller_connection_remote,
    mojo::PendingReceiver<PresentationConnection>
        receiver_connection_receiver) {
  const auto pid_route_it =
      presentation_id_to_route_.find(presentation_info.id);

  if (pid_route_it == presentation_id_to_route_.end()) {
    return;
  }

  if (pid_route_it->second.is_local_presentation()) {
    auto* local_presentation_manager =
        LocalPresentationManagerFactory::GetOrCreateForWebContents(
            web_contents_);
    local_presentation_manager->RegisterLocalPresentationController(
        presentation_info, render_frame_host_id_,
        std::move(controller_connection_remote),
        std::move(receiver_connection_receiver), pid_route_it->second);
  } else {
    MediaRoute::Id route_id = pid_route_it->second.media_route_id();
    if (base::Contains(browser_connection_proxies_, route_id)) {
      return;
    }

    auto* proxy = new BrowserPresentationConnectionProxy(
        router_, route_id, std::move(receiver_connection_receiver),
        std::move(controller_connection_remote));
    browser_connection_proxies_.emplace(route_id, base::WrapUnique(proxy));
  }
}

void PresentationFrame::RemovePresentation(const std::string& presentation_id) {
  // Remove the presentation id mapping so a later call to Reset is a no-op.
  auto it = presentation_id_to_route_.find(presentation_id);
  if (it == presentation_id_to_route_.end()) {
    return;
  }

  auto route_id = it->second.media_route_id();
  presentation_id_to_route_.erase(presentation_id);
  browser_connection_proxies_.erase(route_id);
  // We keep the PresentationConnectionStateChangedCallback registered with MR
  // so the MRP can tell us when terminate() completed.
}

void PresentationFrame::ListenForConnectionStateChange(
    const PresentationInfo& connection,
    const content::PresentationConnectionStateChangedCallback&
        state_changed_cb) {
  auto it = presentation_id_to_route_.find(connection.id);
  if (it == presentation_id_to_route_.end()) {
    return;
  }

  const MediaRoute::Id& route_id = it->second.media_route_id();
  if (connection_state_subscriptions_.find(route_id) !=
      connection_state_subscriptions_.end()) {
    return;
  }

  connection_state_subscriptions_.emplace(
      route_id, router_->AddPresentationConnectionStateChangedCallback(
                    route_id, state_changed_cb));
}

ControllerPresentationServiceDelegateImpl::
    ControllerPresentationServiceDelegateImpl(
        content::WebContents* web_contents)
    : content::WebContentsUserData<ControllerPresentationServiceDelegateImpl>(
          *web_contents),
      router_(MediaRouterFactory::GetApiForBrowserContext(
          web_contents->GetBrowserContext())) {
  DCHECK(router_);
}

ControllerPresentationServiceDelegateImpl::
    ~ControllerPresentationServiceDelegateImpl() = default;

void ControllerPresentationServiceDelegateImpl::AddObserver(
    int render_process_id,
    int render_frame_id,
    DelegateObserver* observer) {
  DCHECK(observer);
  observers_.AddObserver(render_process_id, render_frame_id, observer);
}

void ControllerPresentationServiceDelegateImpl::RemoveObserver(
    int render_process_id,
    int render_frame_id) {
  observers_.RemoveObserver(render_process_id, render_frame_id);
}

bool ControllerPresentationServiceDelegateImpl::AddScreenAvailabilityListener(
    int render_process_id,
    int render_frame_id,
    content::PresentationScreenAvailabilityListener* listener) {
  DCHECK(listener);
  content::GlobalRenderFrameHostId render_frame_host_id(render_process_id,
                                                        render_frame_id);
  auto* presentation_frame = GetOrAddPresentationFrame(render_frame_host_id);
  return presentation_frame->SetScreenAvailabilityListener(listener);
}

void ControllerPresentationServiceDelegateImpl::
    RemoveScreenAvailabilityListener(
        int render_process_id,
        int render_frame_id,
        content::PresentationScreenAvailabilityListener* listener) {
  DCHECK(listener);
  content::GlobalRenderFrameHostId render_frame_host_id(render_process_id,
                                                        render_frame_id);
  const auto it = presentation_frames_.find(render_frame_host_id);
  if (it != presentation_frames_.end()) {
    it->second->RemoveScreenAvailabilityListener(listener);
  }
}

void ControllerPresentationServiceDelegateImpl::Reset(int render_process_id,
                                                      int render_frame_id) {
  content::GlobalRenderFrameHostId render_frame_host_id(render_process_id,
                                                        render_frame_id);
  const auto it = presentation_frames_.find(render_frame_host_id);
  if (it != presentation_frames_.end()) {
    it->second->Reset();
    presentation_frames_.erase(it);
  }

  if (default_presentation_request_ &&
      render_frame_host_id ==
          default_presentation_request_->render_frame_host_id) {
    ClearDefaultPresentationRequest();
  }
}

PresentationFrame*
ControllerPresentationServiceDelegateImpl::GetOrAddPresentationFrame(
    const content::GlobalRenderFrameHostId& render_frame_host_id) {
  auto& presentation_frame = presentation_frames_[render_frame_host_id];
  if (!presentation_frame) {
    presentation_frame = std::make_unique<PresentationFrame>(
        render_frame_host_id, &GetWebContents(), router_);
  }
  return presentation_frame.get();
}

void ControllerPresentationServiceDelegateImpl::SetDefaultPresentationUrls(
    const content::PresentationRequest& request,
    content::DefaultPresentationConnectionCallback callback) {
  if (request.presentation_urls.empty()) {
    ClearDefaultPresentationRequest();
    return;
  }

  DCHECK(!callback.is_null());
  default_presentation_started_callback_ = std::move(callback);
  default_presentation_request_ = request;
  NotifyDefaultPresentationChanged(&request);
}

void ControllerPresentationServiceDelegateImpl::OnJoinRouteResponse(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const GURL& presentation_url,
    const std::string& presentation_id,
    content::PresentationConnectionCallback success_cb,
    content::PresentationConnectionErrorCallback error_cb,
    mojom::RoutePresentationConnectionPtr connection,
    const RouteRequestResult& result) {
  if (!result.route()) {
    std::move(error_cb).Run(PresentationError(
        PresentationErrorType::NO_PRESENTATION_FOUND, result.error()));
  } else {
    DCHECK_EQ(presentation_id, result.presentation_id());
    PresentationInfo presentation_info(presentation_url,
                                       result.presentation_id());
    AddPresentation(render_frame_host_id, presentation_info, *result.route());
    EnsurePresentationConnection(render_frame_host_id, presentation_info,
                                 &connection);
    std::move(success_cb)
        .Run(blink::mojom::PresentationConnectionResult::New(
            presentation_info.Clone(), std::move(connection->connection_remote),
            std::move(connection->connection_receiver)));
  }
}

void ControllerPresentationServiceDelegateImpl::OnStartPresentationSucceeded(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    content::PresentationConnectionCallback success_cb,
    const PresentationInfo& new_presentation_info,
    mojom::RoutePresentationConnectionPtr connection,
    const MediaRoute& route) {
  AddPresentation(render_frame_host_id, new_presentation_info, route);
  EnsurePresentationConnection(render_frame_host_id, new_presentation_info,
                               &connection);
  std::move(success_cb)
      .Run(blink::mojom::PresentationConnectionResult::New(
          new_presentation_info.Clone(),
          std::move(connection->connection_remote),
          std::move(connection->connection_receiver)));
}

void ControllerPresentationServiceDelegateImpl::AddPresentation(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const PresentationInfo& presentation_info,
    const MediaRoute& route) {
  auto* presentation_frame = GetOrAddPresentationFrame(render_frame_host_id);
  presentation_frame->AddPresentation(presentation_info, route);
  NotifyMediaRoutesChanged();
}

void ControllerPresentationServiceDelegateImpl::RemovePresentation(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const std::string& presentation_id) {
  const auto it = presentation_frames_.find(render_frame_host_id);
  if (it != presentation_frames_.end()) {
    it->second->RemovePresentation(presentation_id);
  }
  NotifyMediaRoutesChanged();
}

void ControllerPresentationServiceDelegateImpl::StartPresentation(
    const content::PresentationRequest& request,
    content::PresentationConnectionCallback success_cb,
    content::PresentationConnectionErrorCallback error_cb) {
  const auto& render_frame_host_id = request.render_frame_host_id;
  const auto& presentation_urls = request.presentation_urls;
  if (presentation_urls.empty()) {
    std::move(error_cb).Run(PresentationError(
        PresentationErrorType::UNKNOWN, "Invalid presentation arguments."));
    return;
  }
  if (!std::ranges::all_of(presentation_urls, IsValidPresentationUrl)) {
    std::move(error_cb).Run(
        PresentationError(PresentationErrorType::NO_PRESENTATION_FOUND,
                          "Invalid presentation URL."));
    return;
  }
  auto presentation_context = std::make_unique<StartPresentationContext>(
      request,
      base::BindOnce(&ControllerPresentationServiceDelegateImpl::
                         OnStartPresentationSucceeded,
                     weak_factory_.GetWeakPtr(), render_frame_host_id,
                     std::move(success_cb)),
      std::move(error_cb));
  if (start_presentation_cb_) {
    start_presentation_cb_.Run(std::move(presentation_context));
    return;
  }
  MediaRouterDialogController* controller =
      MediaRouterDialogController::GetOrCreateForWebContents(&GetWebContents());
  controller->ShowMediaRouterDialogForPresentation(
      std::move(presentation_context));
}

void ControllerPresentationServiceDelegateImpl::ReconnectPresentation(
    const content::PresentationRequest& request,
    const std::string& presentation_id,
    content::PresentationConnectionCallback success_cb,
    content::PresentationConnectionErrorCallback error_cb) {
  const auto& presentation_urls = request.presentation_urls;
  const auto& render_frame_host_id = request.render_frame_host_id;
  if (presentation_urls.empty()) {
    std::move(error_cb).Run(
        PresentationError(PresentationErrorType::NO_PRESENTATION_FOUND,
                          "Invalid presentation arguments."));
    return;
  }

  auto* local_presentation_manager =
      LocalPresentationManagerFactory::GetOrCreateForWebContents(
          &GetWebContents());
  // Check local presentation across frames.
  if (local_presentation_manager->IsLocalPresentation(presentation_id)) {
    auto* route = local_presentation_manager->GetRoute(presentation_id);

    if (!route ||
        !base::Contains(presentation_urls, route->media_source().url())) {
      return;
    }

    auto result = RouteRequestResult::FromSuccess(*route, presentation_id);
    OnJoinRouteResponse(render_frame_host_id, presentation_urls[0],
                        presentation_id, std::move(success_cb),
                        std::move(error_cb),
                        mojom::RoutePresentationConnectionPtr(), *result);
  } else {
    // TODO(crbug.com/1418744): Handle multiple URLs.
    const GURL& presentation_url = presentation_urls[0];
    router_->JoinRoute(
        MediaSource::ForPresentationUrl(presentation_url).id(), presentation_id,
        request.frame_origin, &GetWebContents(),
        base::BindOnce(
            &ControllerPresentationServiceDelegateImpl::OnJoinRouteResponse,
            weak_factory_.GetWeakPtr(), render_frame_host_id, presentation_url,
            presentation_id, std::move(success_cb), std::move(error_cb)),
        base::TimeDelta());
  }
}

void ControllerPresentationServiceDelegateImpl::CloseConnection(
    int render_process_id,
    int render_frame_id,
    const std::string& presentation_id) {
  const content::GlobalRenderFrameHostId rfh_id(render_process_id,
                                                render_frame_id);
  auto route_id = GetRouteId(rfh_id, presentation_id);
  if (route_id.empty()) {
    return;
  }

  auto* local_presentation_manager =
      LocalPresentationManagerFactory::GetOrCreateForWebContents(
          &GetWebContents());

  if (local_presentation_manager->IsLocalPresentation(presentation_id)) {
    local_presentation_manager->UnregisterLocalPresentationController(
        presentation_id, rfh_id);
  } else {
    router_->DetachRoute(route_id);
  }
  RemovePresentation(rfh_id, presentation_id);
  // TODO(mfoltz): close() should always succeed so there is no need to keep the
  // state_changed_cb around - remove it and fire the ChangeEvent on the
  // PresentationConnection in Blink.
}

void ControllerPresentationServiceDelegateImpl::Terminate(
    int render_process_id,
    int render_frame_id,
    const std::string& presentation_id) {
  const content::GlobalRenderFrameHostId rfh_id(render_process_id,
                                                render_frame_id);
  auto route_id = GetRouteId(rfh_id, presentation_id);
  if (route_id.empty()) {
    return;
  }
  router_->TerminateRoute(route_id);
  RemovePresentation(rfh_id, presentation_id);
}

void ControllerPresentationServiceDelegateImpl::ListenForConnectionStateChange(
    int render_process_id,
    int render_frame_id,
    const PresentationInfo& connection,
    const content::PresentationConnectionStateChangedCallback&
        state_changed_cb) {
  content::GlobalRenderFrameHostId render_frame_host_id(render_process_id,
                                                        render_frame_id);
  const auto it = presentation_frames_.find(render_frame_host_id);
  if (it != presentation_frames_.end()) {
    it->second->ListenForConnectionStateChange(
        connection,
        base::BindRepeating(&ControllerPresentationServiceDelegateImpl::
                                OnConnectionStateChanged,
                            weak_factory_.GetWeakPtr(), render_frame_host_id,
                            connection, state_changed_cb));
  }
}

void ControllerPresentationServiceDelegateImpl::AddObserver(
    content::PresentationObserver* observer) {
  presentation_observers_.AddObserver(observer);
}

void ControllerPresentationServiceDelegateImpl::RemoveObserver(
    content::PresentationObserver* observer) {
  presentation_observers_.RemoveObserver(observer);
}

bool ControllerPresentationServiceDelegateImpl::HasDefaultPresentationRequest()
    const {
  return default_presentation_request_.has_value();
}

const content::PresentationRequest&
ControllerPresentationServiceDelegateImpl::GetDefaultPresentationRequest()
    const {
  DCHECK(HasDefaultPresentationRequest());
  return *default_presentation_request_;
}

void ControllerPresentationServiceDelegateImpl::OnPresentationResponse(
    const content::PresentationRequest& presentation_request,
    mojom::RoutePresentationConnectionPtr connection,
    const RouteRequestResult& result) {
  if (!result.route() || !base::Contains(presentation_request.presentation_urls,
                                         result.presentation_url())) {
    return;
  }

  PresentationInfo presentation_info(result.presentation_url(),
                                     result.presentation_id());
  AddPresentation(presentation_request.render_frame_host_id, presentation_info,
                  *result.route());
  if (default_presentation_request_ &&
      ArePresentationRequestsEqual(*default_presentation_request_,
                                   presentation_request)) {
    EnsurePresentationConnection(presentation_request.render_frame_host_id,
                                 presentation_info, &connection);
    default_presentation_started_callback_.Run(
        blink::mojom::PresentationConnectionResult::New(
            presentation_info.Clone(), std::move(connection->connection_remote),
            std::move(connection->connection_receiver)));
  } else {
    DCHECK(!connection);
  }
}
std::vector<MediaRoute>
ControllerPresentationServiceDelegateImpl::GetMediaRoutes() {
  std::vector<MediaRoute> routes;
  for (const auto& presentation_frame : presentation_frames_) {
    for (const auto& route :
         presentation_frame.second->presentation_id_to_route()) {
      routes.push_back(route.second);
    }
  }
  return routes;
}

base::WeakPtr<WebContentsPresentationManager>
ControllerPresentationServiceDelegateImpl::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool ControllerPresentationServiceDelegateImpl::
    HasScreenAvailabilityListenerForTest(
        int render_process_id,
        int render_frame_id,
        const MediaSource::Id& source_id) const {
  content::GlobalRenderFrameHostId render_frame_host_id(render_process_id,
                                                        render_frame_id);
  const auto it = presentation_frames_.find(render_frame_host_id);
  return it != presentation_frames_.end() &&
         it->second->HasScreenAvailabilityListenerForTest(source_id);
}

void ControllerPresentationServiceDelegateImpl::
    ClearDefaultPresentationRequest() {
  default_presentation_started_callback_.Reset();
  if (!default_presentation_request_) {
    return;
  }

  default_presentation_request_.reset();
  NotifyDefaultPresentationChanged(nullptr);
}

std::unique_ptr<media::FlingingController>
ControllerPresentationServiceDelegateImpl::GetFlingingController(
    int render_process_id,
    int render_frame_id,
    const std::string& presentation_id) {
  const content::GlobalRenderFrameHostId rfh_id(render_process_id,
                                                render_frame_id);
  MediaRoute::Id route_id = GetRouteId(rfh_id, presentation_id);

  if (route_id.empty()) {
    return nullptr;
  }

  return router_->GetFlingingController(route_id);
}

MediaRoute::Id ControllerPresentationServiceDelegateImpl::GetRouteId(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const std::string& presentation_id) const {
  const auto it = presentation_frames_.find(render_frame_host_id);
  return it != presentation_frames_.end()
             ? it->second->GetRouteId(presentation_id)
             : MediaRoute::Id();
}

void ControllerPresentationServiceDelegateImpl::EnsurePresentationConnection(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const PresentationInfo& presentation_info,
    mojom::RoutePresentationConnectionPtr* connection) {
  // This is where we ensure we have a valid Mojo pipe pair when starting or
  // joining a presentation.  If the MRP chose not return a pair of pipes
  // directly, we need to provide a BrowserPresentationConnectionProxy here or
  // connect to the LocalPresentationManager, as necessary.
  if (!*connection) {
    mojo::PendingRemote<PresentationConnection> controller_remote;
    mojo::PendingRemote<PresentationConnection> receiver_remote;
    *connection = mojom::RoutePresentationConnection::New(
        std::move(receiver_remote),
        controller_remote.InitWithNewPipeAndPassReceiver());
    auto* presentation_frame = GetOrAddPresentationFrame(render_frame_host_id);
    presentation_frame->ConnectToPresentation(
        presentation_info, std::move(controller_remote),
        (*connection)->connection_remote.InitWithNewPipeAndPassReceiver());
  }
}

void ControllerPresentationServiceDelegateImpl::
    NotifyDefaultPresentationChanged(
        const content::PresentationRequest* request) {
  for (auto& presentation_observer : presentation_observers_) {
    presentation_observer.OnDefaultPresentationChanged(request);
  }
}

void ControllerPresentationServiceDelegateImpl::NotifyMediaRoutesChanged() {
  auto routes = GetMediaRoutes();

  for (auto& presentation_observer : presentation_observers_) {
    presentation_observer.OnPresentationsChanged(!routes.empty());
  }
}

void ControllerPresentationServiceDelegateImpl::OnConnectionStateChanged(
    const content::GlobalRenderFrameHostId& render_frame_host_id,
    const PresentationInfo& connection,
    const content::PresentationConnectionStateChangedCallback& state_changed_cb,
    const content::PresentationConnectionStateChangeInfo& info) {
  if (info.state == blink::mojom::PresentationConnectionState::CLOSED ||
      info.state == blink::mojom::PresentationConnectionState::TERMINATED) {
    RemovePresentation(render_frame_host_id, connection.id);
  }

  state_changed_cb.Run(info);
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(ControllerPresentationServiceDelegateImpl);

}  // namespace media_router