Reland "[Media History] Fix watchtime recording"

This is a reland of c5b00d82d8a218f28296851c4b31e73eb9795822

Original change's description:
> [Media History] Fix watchtime recording
>
> Media History does not always record watchtime
> because the callback might be called after
> the WebContentsObserver has been destroyed.
> This moves it to WebContentsDelegate and adds
> some tests.
>
> BUG=1051176
>
> Change-Id: Ic60066535e3039cee07b2d0994c97e0279bd36e0
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2051289
> Reviewed-by: Kinuko Yasuda <[email protected]>
> Reviewed-by: Elly Fong-Jones <[email protected]>
> Reviewed-by: Tommy Steimel <[email protected]>
> Commit-Queue: Becca Hughes <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#749888}

Bug: 1051176
Change-Id: I365af299c128d5c68e8387ff55691614da82be71
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2105404
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Elly Fong-Jones <[email protected]>
Commit-Queue: Becca Hughes <[email protected]>
Cr-Commit-Position: refs/heads/master@{#750970}
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc
index 5e9496e..1e0d0a2 100644
--- a/content/browser/web_contents/web_contents_impl.cc
+++ b/content/browser/web_contents/web_contents_impl.cc
@@ -7311,18 +7311,15 @@
     observer.AudioContextPlaybackStopped(audio_context_id);
 }
 
-void WebContentsImpl::MediaWatchTimeChanged(
-    const content::MediaPlayerWatchTime& watch_time) {
-  for (auto& observer : observers_)
-    observer.MediaWatchTimeChanged(watch_time);
-}
-
 media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
 WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
+  if (!delegate_ || !delegate_->GetDelegateWeakPtr())
+    return base::DoNothing();
+
   return base::BindRepeating(
-      [](base::WeakPtr<RenderFrameHostDelegate> delegate,
-         GURL last_committed_url, base::TimeDelta total_watch_time,
-         base::TimeDelta time_stamp, bool has_video, bool has_audio) {
+      [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
+         base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
+         bool has_video, bool has_audio) {
         content::MediaPlayerWatchTime watch_time(
             last_committed_url, last_committed_url.GetOrigin(),
             total_watch_time, time_stamp, has_video, has_audio);
@@ -7331,7 +7328,7 @@
         if (delegate)
           delegate->MediaWatchTimeChanged(watch_time);
       },
-      weak_factory_.GetWeakPtr(), GetMainFrameLastCommittedURL());
+      delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
 }
 
 RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(