File: ambient_metrics.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 (375 lines) | stat: -rw-r--r-- 14,120 bytes parent folder | download | duplicates (6)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/ambient/metrics/ambient_metrics.h"

#include <optional>
#include <string>
#include <string_view>
#include <utility>

#include "ash/ambient/ambient_ui_settings.h"
#include "ash/public/cpp/ambient/ambient_ui_model.h"
#include "ash/public/cpp/ambient/common/ambient_settings.h"
#include "ash/public/cpp/ash_web_view.h"
#include "ash/webui/personalization_app/mojom/personalization_app.mojom-shared.h"
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/url_util.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "url/gurl.h"

namespace ash {
namespace ambient {

namespace {

// Histograms default to exponential bucketing, so the smallest bucket occupies
// 24 hours / (2 ^ (144 - 1)) milliseconds. Exponential bucketing is desirable
// for engagement time because most users exit screensaver on the order of
// several minutes, while a small fraction of users exit screensaver after
// many hours. So the histogram's highest resolution should occupy the smaller
// engagement times.
constexpr int kAmbientModeElapsedTimeHistogramBuckets = 144;

// Fields of the JSON dictionary that the ambient video HTML sends to C++ to
// communicate playback metrics.
//
// Whether or not playback started successfully.
constexpr std::string_view kVideoFieldPlaybackStarted = "playback_started";
//
// These reflect the VideoPlaybackQuality JS API:
// https://developer.mozilla.org/en-US/docs/Web/API/VideoPlaybackQuality
//
// Total number of video frames dropped since playback started.
constexpr std::string_view kVideoFieldDroppedFrames = "dropped_frames";
// Total number of video frames expected since playback started (frames
// created + frames dropped).
constexpr std::string_view kVideoFieldTotalFrames = "total_frames";

std::string GetHistogramName(const char* prefix, bool tablet_mode) {
  std::string histogram = prefix;
  if (tablet_mode) {
    histogram += ".TabletMode";
  } else {
    histogram += ".ClamshellMode";
  }

  return histogram;
}

void RecordEngagementTime(const std::string& histogram_name,
                          base::TimeDelta engagement_time) {
  base::UmaHistogramCustomTimes(
      histogram_name,
      /*sample=*/engagement_time,
      // There is no value in bucketing engagement times that are on the order
      // of milliseconds. A 1 second minimum is imposed here but not in the
      // metric above for legacy reasons (the metric above was already pushed
      // to the field and established before this change was made).
      /*min=*/base::Seconds(1),
      /*max=*/base::Hours(24),
      /*buckets=*/kAmbientModeElapsedTimeHistogramBuckets);
}

// After the JSON in the URL fragment has been decoded in `result`:
void OnAmbientVideoPlaybackMetricsParsed(
    base::OnceCallback<void(base::Value::Dict)> completion_cb,
    data_decoder::DataDecoder::ValueOrError result) {
  CHECK(completion_cb);
  // These errors really shouldn't ever happen, but they're not significant
  // enough to crash the whole process over.
  if (!result.has_value()) {
    LOG(ERROR) << "JSON parsing failed with error: " << result.error();
    std::move(completion_cb).Run(base::Value::Dict());
    return;
  }
  if (!result->is_dict()) {
    LOG(ERROR) << "Expected JSON dictionary for metrics";
    std::move(completion_cb).Run(base::Value::Dict());
    return;
  }
  std::move(completion_cb).Run(std::move(*result).TakeDict());
}

// Retrieves the the JSON dictionary in the `web_view`'s URL fragment.
void GetAmbientVideoPlaybackMetrics(
    AshWebView* web_view,
    base::OnceCallback<void(base::Value::Dict)> completion_cb) {
  CHECK(web_view);
  CHECK(completion_cb);
  // The URL fragment identifier is used as a way of communicating the playback
  // metrics data without using any elaborate frameworks or permissions
  // (ex: a WebUI).
  std::string serialized_playback_metrics =
      net::UnescapePercentEncodedUrl(web_view->GetVisibleURL().ref());
  if (serialized_playback_metrics.empty()) {
    // This can legitimately happen if the ambient video is still being loaded
    // and it's still unclear whether playback has started successfully or
    // failed.
    DVLOG(2) << "Ambient video still loading";
    std::move(completion_cb).Run(base::Value::Dict());
    return;
  }
  data_decoder::DataDecoder::ParseJsonIsolated(
      serialized_playback_metrics,
      base::BindOnce(&OnAmbientVideoPlaybackMetricsParsed,
                     std::move(completion_cb)));
}

AmbientVideoSessionStatus ParseAmbientVideoSessionStatus(
    const base::Value::Dict& playback_metrics) {
  std::optional<bool> playback_started =
      playback_metrics.FindBool(kVideoFieldPlaybackStarted);
  if (playback_started.has_value()) {
    return *playback_started ? AmbientVideoSessionStatus::kSuccess
                             : AmbientVideoSessionStatus::kFailed;
  } else {
    // `playback_started` is not set in the URL fragment identifier until it's
    // clear that playback has definitely started successfully or failed.
    return AmbientVideoSessionStatus::kLoading;
  }
}

// `GetAmbientModeVideoSessionStatus()` continued:
// After the `playback_metrics` have been parsed from the URL fragment:
void CompleteGetAmbientVideoSessionStatus(
    base::OnceCallback<void(AmbientVideoSessionStatus)> completion_cb,
    base::Value::Dict playback_metrics) {
  CHECK(completion_cb);
  std::move(completion_cb)
      .Run(ParseAmbientVideoSessionStatus(playback_metrics));
}

// `RecordAmbientModeVideoSessionStatus()` continued:
// After the `AmbientVideoSessionStatus` has been parsed from the URL fragment:
void RecordAmbientModeVideoSessionStatusInternal(
    const AmbientUiSettings& ui_settings,
    AmbientVideoSessionStatus status) {
  base::UmaHistogramEnumeration(
      /*name=*/base::StrCat(
          {"Ash.AmbientMode.VideoPlaybackStatus.", ui_settings.ToString()}),
      status);
}

// `RecordAmbientModeVideoSmoothness()` continued:
// After the `playback_metrics` have been parsed from the URL fragment:
void RecordAmbientModeVideoSmoothnessInternal(
    const AmbientUiSettings& ui_settings,
    base::Value::Dict playback_metrics) {
  CHECK_EQ(ui_settings.theme(),
           personalization_app::mojom::AmbientTheme::kVideo);
  if (ParseAmbientVideoSessionStatus(playback_metrics) !=
      AmbientVideoSessionStatus::kSuccess) {
    // Just to prevent error log spam below. If playback failed completely,
    // `RecordAmbientModeVideoSessionStatus()` should cover that.
    return;
  }
  std::optional<int> dropped_frames =
      playback_metrics.FindInt(kVideoFieldDroppedFrames);
  // Assuming 24 fps, the ambient session would have to last ~2.83 years before
  // the int overflows. For all intensive purposes, this should not happen.
  std::optional<int> expected_frames =
      playback_metrics.FindInt(kVideoFieldTotalFrames);
  if (!dropped_frames || !expected_frames) {
    LOG(ERROR) << "Received invalid metrics dictionary: " << playback_metrics;
    return;
  }
  if (*dropped_frames < 0 || *expected_frames <= 0 ||
      *dropped_frames > *expected_frames) {
    LOG(ERROR) << "Frame statistics are invalid: " << playback_metrics;
    return;
  }
  int created_frames = *expected_frames - *dropped_frames;
  int smoothness = base::ClampRound(
      100.f * (static_cast<float>(created_frames) / *expected_frames));
  base::UmaHistogramPercentage(base::StrCat({"Ash.AmbientMode.VideoSmoothness.",
                                             ui_settings.ToString()}),
                               smoothness);
}

}  // namespace

AmbientModePhotoSource AmbientSettingsToPhotoSource(
    const AmbientSettings& settings) {
  if (settings.topic_source ==
      ash::personalization_app::mojom::TopicSource::kArtGallery) {
    return AmbientModePhotoSource::kArtGallery;
  }

  if (settings.selected_album_ids.size() == 0) {
    return AmbientModePhotoSource::kGooglePhotosEmpty;
  }

  bool has_recent_highlights = base::Contains(
      settings.selected_album_ids, ash::kAmbientModeRecentHighlightsAlbumId);

  if (has_recent_highlights && settings.selected_album_ids.size() == 1) {
    return AmbientModePhotoSource::kGooglePhotosRecentHighlights;
  }

  if (has_recent_highlights && settings.selected_album_ids.size() > 1) {
    return AmbientModePhotoSource::kGooglePhotosBoth;
  }

  return AmbientModePhotoSource::kGooglePhotosPersonalAlbum;
}

void RecordAmbientModeActivation(AmbientUiMode ui_mode, bool tablet_mode) {
  base::UmaHistogramEnumeration(
      GetHistogramName("Ash.AmbientMode.Activation", tablet_mode), ui_mode);
}

void RecordAmbientModeTimeElapsed(base::TimeDelta time_delta,
                                  bool tablet_mode,
                                  const AmbientUiSettings& ui_settings) {
  base::UmaHistogramCustomTimes(
      /*name=*/GetHistogramName("Ash.AmbientMode.EngagementTime", tablet_mode),
      /*sample=*/time_delta,
      /*min=*/base::Hours(0),
      /*max=*/base::Hours(24),
      /*buckets=*/kAmbientModeElapsedTimeHistogramBuckets);

  RecordEngagementTime(
      base::StrCat({"Ash.AmbientMode.EngagementTime.", ui_settings.ToString()}),
      time_delta);
}

void RecordAmbientModeTopicSource(
    const ash::personalization_app::mojom::TopicSource topic_source) {
  base::UmaHistogramEnumeration("Ash.AmbientMode.TopicSource", topic_source);
}

void RecordAmbientModeTotalNumberOfAlbums(int num_albums) {
  base::UmaHistogramCounts100("Ash.AmbientMode.TotalNumberOfAlbums",
                              num_albums);
}

void RecordAmbientModeSelectedNumberOfAlbums(int num_albums) {
  base::UmaHistogramCounts100("Ash.AmbientMode.SelectedNumberOfAlbums",
                              num_albums);
}

void RecordAmbientModeAnimationSmoothness(
    int smoothness,
    const AmbientUiSettings& ui_settings) {
  base::UmaHistogramPercentage(
      base::StrCat({"Ash.AmbientMode.LottieAnimationSmoothness.",
                    ui_settings.ToString()}),
      smoothness);
}

void RecordAmbientModeStartupTime(base::TimeDelta startup_time,
                                  const AmbientUiSettings& ui_settings) {
  base::UmaHistogramCustomTimes(
      /*name=*/base::StrCat(
          {"Ash.AmbientMode.StartupTime.", ui_settings.ToString()}),
      /*sample=*/startup_time,
      /*min=*/base::Seconds(0),
      /*max=*/kMetricsStartupTimeMax,
      /*buckets=*/50);
}

void GetAmbientModeVideoSessionStatus(
    AshWebView* web_view,
    base::OnceCallback<void(AmbientVideoSessionStatus)> completion_cb) {
  CHECK(completion_cb);
  if (web_view->IsErrorDocument()) {
    // There was an issue loading the actual html.
    std::move(completion_cb).Run(AmbientVideoSessionStatus::kFailed);
    return;
  }
  GetAmbientVideoPlaybackMetrics(
      web_view, base::BindOnce(&CompleteGetAmbientVideoSessionStatus,
                               std::move(completion_cb)));
}

void RecordAmbientModeVideoSessionStatus(AshWebView* web_view,
                                         const AmbientUiSettings& ui_settings) {
  GetAmbientModeVideoSessionStatus(
      web_view, base::BindOnce(&RecordAmbientModeVideoSessionStatusInternal,
                               ui_settings));
}

void RecordAmbientModeVideoSmoothness(AshWebView* web_view,
                                      const AmbientUiSettings& ui_settings) {
  GetAmbientVideoPlaybackMetrics(
      web_view,
      base::BindOnce(&RecordAmbientModeVideoSmoothnessInternal, ui_settings));
}

AmbientOrientationMetricsRecorder::AmbientOrientationMetricsRecorder(
    views::View* root_rendering_view,
    const AmbientUiSettings& ui_settings)
    : settings_(ui_settings.ToString()) {
  root_rendering_view_observer_.Observe(root_rendering_view);
  // Capture initial orientation with manual call.
  OnViewBoundsChanged(root_rendering_view);
}

AmbientOrientationMetricsRecorder::~AmbientOrientationMetricsRecorder() {
  SaveCurrentOrientationDuration();
  if (!total_portrait_duration_.is_zero()) {
    RecordEngagementTime(
        base::StringPrintf("Ash.AmbientMode.EngagementTime.%s.Portrait",
                           settings_.data()),
        total_portrait_duration_);
  }
  if (!total_landscape_duration_.is_zero()) {
    RecordEngagementTime(
        base::StringPrintf("Ash.AmbientMode.EngagementTime.%s.Landscape",
                           settings_.data()),
        total_landscape_duration_);
  }
}

void AmbientOrientationMetricsRecorder::OnViewBoundsChanged(
    views::View* observed_view) {
  DCHECK(observed_view);
  gfx::Rect content_bounds = observed_view->GetContentsBounds();
  if (content_bounds.IsEmpty()) {
    DVLOG(4) << "Initial view layout has not occurred yet. Ignoring empty view "
                "bounds";
    return;
  }

  bool new_orientation_is_portrait =
      content_bounds.width() < content_bounds.height();
  if (current_orientation_is_portrait_.has_value() &&
      *current_orientation_is_portrait_ == new_orientation_is_portrait) {
    return;
  }

  SaveCurrentOrientationDuration();
  current_orientation_is_portrait_.emplace(new_orientation_is_portrait);
  // Effectively stops the existing timer and starts new one.
  current_orientation_timer_.emplace();
}

void AmbientOrientationMetricsRecorder::SaveCurrentOrientationDuration() {
  if (!current_orientation_is_portrait_.has_value() ||
      !current_orientation_timer_.has_value()) {
    return;
  }

  if (*current_orientation_is_portrait_) {
    total_portrait_duration_ += current_orientation_timer_->Elapsed();
  } else {
    total_landscape_duration_ += current_orientation_timer_->Elapsed();
  }
}

}  // namespace ambient
}  // namespace ash